从UITableView中使用cellForRowAtIndexPath获取UITableViewCell

4

我正在尝试从我的UITableViewController中获取一个子类化的UITableViewCell(类名为'MasterCell'),并且IndexPath是可变的。比如说,我想要获取第一行的单元格:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
MasterCell *cell = (MasterCell *)[self.tableView cellForRowAtIndexPath:indexPath];

这个问题发生在我的viewWillAppear方法中。不幸的是,在调试时cell为空。

我有不同的单元格/行,我需要在viewWillAppear方法中更改一些值。你有什么提示吗?


你的意思是从你的故事板中获取一个单元格吗? - Darren
是的,这是一个带有TableViewController的故事板。'self.tableView'是一个属性(IBOutlet UITableView),连接到TableView。 - Fonsi
不要使用indexPath获取单元格。在Storyboard中为其指定一个重用标识符,然后使用MasterCell *cell = (MasterCell *)[tableView dequeueReusableCellWithIdentifier:@"masterCell"]; - Darren
2
只是为了明确,根据你的示例,你实际上正在尝试访问第一个部分中的第二行。它为nil的问题可能是由于单元格不可见(如Martin R所提到的),或者因为您的indexPath超出范围(即在您的表格中没有第一部分的第二行)。http://developer.apple.com/library/ios/documentation/uikit/reference/UITableView_Class/Reference/Reference.html#//apple_ref/occ/instm/UITableView/cellForRowAtIndexPath: - gschandler
1
@gshandler:你是对的,索引超出范围是另一个可能的原因,我忘了提到。- 但无论如何,检索单元格“更改一些值”都不是一个好主意。 - Martin R
IndexPath是正确的,但是单元格不可见。这就是返回nil的原因。现在我可以在下面提到的方法中设置我的单元格中UIStepper的值。运行良好! - Fonsi
1个回答

11

[self.tableView cellForRowAtIndexPath:indexPath]方法返回的是当前可见的单元格,对于当前不可见的单元格则返回nil

你不应该使用单元格来存储你的模型数据,因为当你向上或向下滚动时,单元格会被重用。


非常感谢Darren和Martin R!我可以在方法“-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath”中设置初始值(它实际上是一个UIStepper,其值来自Core Data实体)。 运行良好! - Fonsi
通过 'self.tableView.subviews' 访问怎么样? - LKM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接