我制作了一个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中的观察者.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。