UITableView单元格保留视图数据

时间:2014-06-09 15:50:25

标签: objective-c uitableview retain

我正在尝试解决有关UITableView单元格在屏幕外或可见区域外的问题。

在我的tableview单元格中,我有一个UITextField,我可以使用下面的代码轻松解析。但是我发现对于不可见的单元格,它返回NULL值。

我猜这是一个提高内存使用率的功能,但无论如何要将其关闭?或者如果没有,是否有解决方法?

InputCell *inputCell = (InputCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
UITextField *cellContent = (UITextField *)[inputCell.textInput viewWithTag:0];

NSLog(@"Cell Content: %@" , cellContent.text);

再次感谢和感谢!

1 个答案:

答案 0 :(得分:1)

视图需要模型,尤其是表视图。模型是表示应用程序状态的一些对象(通常是集合类中的一组对象)。表视图需要一个数组。数据源协议要求您描述该数组。由于tableview单元格是视图的一部分,因此不应依赖它们来保持应用程序的状态。这取决于你如下:

在你的vc的私人界面中:

@property(strong, nonatomic) NSMutableArray *myDatasource;

早期,就像在视图中加载一样:

myDatasource = [NSMutableArray array];
// fill it with strings

在numberOfRowsInSection中......:

return self.myDatasource.count;

在cellForRowAtIndexPath中:

cellContent.text = self.myDatasource[indexPath.row];

将vc作为textField的委托并实现:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSString *candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSIndexPath *indexPath = [self indexPathWithSubview:textField];
    self.myDatasource replaceObjectAtIndex:[indexPath.row] withObject: candidateString];
    return YES;
}

此帮助程序查找任何单元格的任何textField(任何子视图)的indexPath:

- (NSIndexPath *)indexPathWithSubview:(UIView *)subview {

    while (![subview isKindOfClass:[UITableViewCell self]] && subview) {
        subview = subview.superview;
    }
    return [self.tableView indexPathForCell:(UITableViewCell *)subview];
}

它看起来很多,但是当你习惯它时并没有那么糟糕。模式始终是 - 想象描述应用(模型)状态的对象。考虑最能描述和操纵该状态(视图)的视图。使视图控制器(控制器)(a)注意模型更改并相应地更改视图,以及(b)从视图中听取用户操作并更新模型。