我在創建自定義UITableViewCell時遇到了難以置信的難度。我已經徹底檢查了stackoverflow和google,但是發佈的所有解決方案都不完整,不正確,或者做得足夠遠。如何正確連接自定義UITableViewCell並訪問元素
所以這就是我想要做的。我想讓MyTableViewController在自定義單元格中加載,我們稱它們爲MyCustomCell,而不是默認單元格。我希望MyCustomCell是UITableViewCell的一個完整的子類,所以我只有一個帶有UITableViewCell的(.xib)和一些測試標籤。單元格標識符被設置爲「MyCustomCell」,並且該類別被設置爲「MyCustomCell」。我可以將標籤拖放到MyCustomCell.h中。
回到MyTableViewController.m,我有下面的代碼
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ident = @"MyCustomCell";
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];//appears to crash here
if(cell == nil){
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:ident owner:self options:nil];
for(id currentObject in topLevelObjects){
if([currentObject isKindOfClass:[MyCustomCell class]]){
cell = (MyCustomCell*)currentObject;
break;
}
}
}
cell.myCustomLabel.text = @"hello world";//myCustomLabel from the .xib is linked up to the
//proper variable in MyCustomCell.h, and it's also being synthesized
//I'd like to modify all the custom labels,imageviews,etc here
return cell;
}
運行這給了我以下錯誤:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<MyTableViewController 0x7d5ba80> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key myCustomLabel.'
這通常出現在當我忘了勾一些.xib和它的.h文件,或者當它不合成,但我已經檢查,似乎工作。有什麼我在這裏做錯了嗎?我必須完成[[MyCustomCell alloc] init]或[[MyCustomCell alloc] initWithCustomMethod:...]嗎?
你的第一個建議似乎沒有奏效。我也再次越過了筆尖,一切看起來都應該起作用。最後,我剛剛刪除了所有內容,從頭開始,現在看起來好像一切正常 – user1601540 2012-08-15 23:45:51