[問題] registerNib:forCellReuseIdentifier:

看板MacDev作者 (狗狗)時間10年前 (2013/08/01 18:50), 編輯推噓3(308)
留言11則, 2人參與, 最新討論串1/1
我有個 .xib 檔,是要客製化 TableViewCell 的 Interface Builder 內的 File Owner 及 該 cell 都有設定為我的 custom class 然後我利用 table view的 registerNib:forCellReuseIdentifier: 來註冊一個 reuseID 及對應的 nib 問題出在 dataSource 的地方 我利用 table view 的 -dequeueReusableCellWithIdentifier: 來得到一個 cell table view 卻給我一個 UITableViewCell 而非我的 custom class 但是 cell 的 UI 介面,的確跟我 nib 檔內的設置是一樣的 但這樣我就沒有 customized cell 的功能了... 請問是我哪裡有弄做什麼? 還是 -dequeueReusableCellWithIdentifier: 的問題 只會回傳 UITableViewCell? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.163.125.199

08/01 19:25, , 1F
(yourCustomCell *)[tableview dequeueReuse....];
08/01 19:25, 1F

08/01 19:26, , 2F
yourCustomCell *cell = [tableview dequeueReusable...];
08/01 19:26, 2F
這邊宣告回傳物件為某個型別 也無法改變該物件原本類別的事實... NSLog(@"cell class: %@", NSStringFromClass([cell class])); 會printt出"UITableViewCell"

08/01 19:26, , 3F
= =我到底在打什麼
08/01 19:26, 3F

08/01 19:27, , 4F
你有照我第二行打的那樣打嗎?你是要在哪裡用到cell?
08/01 19:27, 4F

08/01 19:28, , 5F
cellForRowAtIndexPath?
08/01 19:28, 5F

08/01 19:39, , 6F
你的cell要是你自己的Custom Cell的class才行唷
08/01 19:39, 6F
// data source - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ CustomizedCell *cell = [tableView dequeueReusableCellWithIdentifier:id]; NSLog(@"cell: %@", cell); // 此時cell會存在 而且的確是load Nib的UI // 但是class一直都是UITableViewCell; if (!cell){ NSLog(@"永遠不會進來,因為我已用registerNib:forCellReuseIdentifier:"); // 以前dequeue沒有cell的話 要在這邊手動自己create cell // 可以用 alloc-init 或是在這邊用 nib file 來創造 cell // 但實際上只要register該reuse identifer,dequere時一定有cell // UIKit會根據register的Nib或class 來產生該cell // 所以這邊if statement不會通過 其實這邊不用寫code // 只是好像-dequeueReusableCellWithIdentifier: 創造出來的cell // 都是UITableViewCell... (無論我Nib設file owner/cell的class 都無效) // 不知道真的是bug 還是我漏掉設定什麼? } return cell; } ※ 編輯: leondemon 來自: 114.198.184.235 (08/02 00:23)

08/02 09:46, , 7F
這要等高手啦 XD
08/02 09:46, 7F

08/02 09:47, , 8F
你的意思是,你的cell底下沒有你自己CustomCell的object?
08/02 09:47, 8F

08/02 09:51, , 9F
等高手來之前 要不要把完整code丟上來看看
08/02 09:51, 9F

08/02 10:32, , 10F
08/02 10:32, 10F
後來我找到問題了 雖然不知道是怎麼回事 因為 Xcode 在 subclass UITableViewCell 時 沒有同時產生 xib檔的選項 所以必須自己手動加入一個 .xib 檔 而當初創造該 xib 檔時 從清單中選了empty的選項 才會發生此事 (想說也不是要customize UIView/UIWindow 直接從空白的開始設定) 後來重新建立 .xib 新檔時 選了 View 的 xib 選項 然後把該 view 給刪除掉之後 重新加入一個 table view cell 這樣在 register 之後 就會確實產生我設定的類別物件 只不過我還是不知道 empty 的 xib 檔是要拿來做什麼用的... 還是 empty 的 xib 檔還要設定什麼地方 才能拿來給 table view register? ※ 編輯: leondemon 來自: 118.163.125.199 (08/02 14:03)

08/02 15:23, , 11F
你有連Files Owner的view outlet出去嗎?
08/02 15:23, 11F
文章代碼(AID): #1H-ZsEKs (MacDev)