2

カスタム UITableViewCell を作成するのは非常に困難です。私はstackoverflowとgoogleを徹底的にチェックしましたが、投稿されたすべての解決策は不完全であるか、間違っているか、または十分に進んでいます.

これが私がやりたいことです。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:...] を実行する必要はありますか?

4

1 に答える 1

1

iOS 5 をターゲットにしている場合は、これを使用します。

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

次に、識別子を使用してペン先からセルを取得します

[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

最後に: UITableViewCell サブクラスのペン先に適切なクラス名と適切な識別子を実際に割り当てていることを確認してください。

于 2012-08-15T21:53:59.827 に答える