ios – UITableViewCell将消失

我制作了一个UITableView并包含一些自定义UITableViewCells,在第一个单元格中(例如名为cell0)有一些UITextFields用于输入,当我滚动tableView时,cell0将从屏幕顶部消失,那么我如何获取UITextField的文本在cell0?

cellForRowAtIndexPath将返回nil.

解决方法

根据 Apple Documentation关于cellForRowAtIndexPath:,它返回“表示表格的单元格的对象,如果单元格不可见或者indexPath超出范围,则返回nil”.

根据MVC Pattern,UITableViewCell是一个视图.所以我更喜欢维护一个模型对象 – 也许它就像NSString实例一样简单 – 如果我是你的话,将文本保存在单元格中.您可以通过向控制器添加UITextFieldTextDidChangeNotification键的观察者来观察UITextField的更改.

- (void)textFieldDidChangeText:(NSNotification *)notification
{
    // Assume your controller has a NSString (copy) property named "text".
    self.text = [(UITextField *)[notification object] text]; // The notification's object property will return the UITextField instance who has posted the notification.
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Dequeue cell...
    // ...
    if (!cell)
    {
        // Init cell...
        // ...
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChangeText:) name:UITextFieldTextDidChangeNotification object:yourTextField];
    }

    // Other code...
    // ...
    return cell;
}

不要忘记删除-dealloc中的观察者.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...