カスタムセルを含む UITableView があります。このカスタム セルは、Style "Detail Left" の通常のセルのように見えます。しかし、カスタム セルには詳細ラベルとテキスト フィールドがあり、ユーザーがテキストを編集できるようになっています。ユーザーが入力したすべてのデータを保存する保存ボタンがあります。このチュートリアルを使用してカスタム セルを作成しました: http://agilewarrior.wordpress.com/2012/05/19/how-to-add-a-custom-uitableviewcell-to-a-xib-file-objective-c/ #コメント-4883
ユーザー データを取得するために、テキスト フィールドのデリゲートをテーブル ビュー コントローラー (self) に設定し、textFieldDidEndEditing: メソッドを実装しました。このメソッドでは、テキスト フィールドの親ビュー (= セル) を要求し、このセルの indexPath を要求します。問題は、編集するセルに関係なく、indexPath.row に対して常に 0 を取得することです。私は何を間違っていますか?
これが私のコードです:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:[CustomCell reuseIdentifier] forIndexPath:indexPath];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
cell = self.customCell;
self.customCell = nil;
}
cell.label.text = @"Some label text";
cell.editField.delegate = self;
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
CustomCell *cell = (CustomCell *) textField.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSLog(@"the section is %d and row is %d", indexPath.section, indexPath.row);
...
}
編集:返されたindexPathがnilであることを知りました。したがって、nil の場合は標準値 0 を取得します。それで問題ありません。しかし今: indexPath に nil を取得するのはなぜですか?