2012-05-10 33 views
15

如何使用UINibs實例化並在iOS5.0中使用UITableViewCell作爲tableview。我知道有一個registerNib:forCellReuseIdentifier:在iOS5.0也需要使用,但我不知道如何使用它如何使用UINib實例化並使用自定義的UITableViewCells

預先感謝任何幫助這個

+1

退房此鏈接:http://useyourloaf.com/blog/2011/2/28/speeding-up-table-view-cell-loading -with-uinib.html這應該讓你開始! :) –

回答

41
  1. 創建XIB文件用UITableViewCell作爲頂級對象。這叫做Cell.xib
  2. 根據這個文件創建一個UINib對象
  3. 註冊帶有表視圖的UINib(通常在你的表視圖控制器子類的viewDidLoad中)。

步驟2和3可以合併,所以你會使用viewDidLoad中下面一行:

[self.tableView registerNib:[UINib nibWithNibName:@"Cell" bundle:nil] forCellReuseIdentifier:@"Cell"]; 

然後,在的cellForRowAtIndexPath,如果你想從筆尖的一個細胞,你出列,它:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"]; 

這可以從筆尖創建新實例,或者使現有單元出列。

+2

我其實只是自己實現了Cell Reuse Identifier,它工作的很好! –

+1

您的解決方案絕對正確,但不幸的是iOS 5中有一個錯誤(在iOS 6中修復)與VoiceOver配合使用:http://openradar.appspot.com/11549999 –

+0

加載單元格時,我想以編程方式自定義背景顏色(因爲bg顏色是圖案圖像)。可能嗎? – Satyam

1

@jrturtons答案是正確的,但不幸的是iOS 5中有一個錯誤(在iOS 6中修復)與VoiceOver結合使用:rdar://11549999UITableView上的以下類別解決了此問題。只需使用-fixedDequeueReusableCellWithIdentifier:而不是正常的dequeueReusableCellWithIdentifier:。當然,NIB必須註冊使用

[self.tableView registerNib:[UINib nibWithNibName:@"Cell" bundle:nil] forCellReuseIdentifier:@"Cell"]; 

之前(在-viewDidLoad)。

的UITableView + Workaround.m:

@implementation UITableView (Workaround) 
- (id)fixedDequeueReusableCellWithIdentifier:(NSString *)identifier { 
    id cell = [self dequeueReusableCellWithIdentifier:identifier]; 
    if (!cell) { 
     // fix for rdar://11549999 (registerNib… fails on iOS 5 if VoiceOver is enabled) 
     cell = [[[NSBundle mainBundle] loadNibNamed:identifier owner:self options:nil] objectAtIndex:0]; 
    } 
    return cell; 
} 
@end 
+0

我已經多次閱讀過這個bug,但從未體驗過它 - 即使在iOS 5.0上運行VoiceOver時也是如此。我相信實際問題比這更復雜。 –

+0

這就是說,我懷疑你的解決方法總是有效的:太棒了! :) –

相關問題