6

カスタムセルを含む 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 を取得するのはなぜですか?

4

2 に答える 2

5

私は自分で解決策を見つけました。スーパービューのコードは、stackoverflow で見つけたので、コピーしました。しかし、それはうまくいきません。次のような 2 つのスーパービューを実行する必要があります。

CustomCell *cell = (CustomCell *) textField.superview.superview;

今では正常に動作します!

于 2012-10-12T12:58:28.233 に答える
0

indexプロパティを CustomCell に追加して、indexPath.row内部に入力していただけますか(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

于 2012-10-12T12:15:30.537 に答える