【问题标题】:Get UITableViewCell from UITableView with cellForRowAtIndexPath使用 cellForRowAtIndexPath 从 UITableView 获取 UITableViewCell
【发布时间】:2012-09-01 15:19:42
【问题描述】:

我正在尝试从我的 UITableViewController 中获取一个子类 UITableViewCell(类称为“MasterCell”),并更改 IndexPath。假设,我将获取第一行的单元格:

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

这发生在我的 viewWillAppear 方法中。不幸的是,调试时单元格为零。

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

【问题讨论】:

  • 你的意思是你试图从你的故事板中获取一个单元格吗?
  • 是的,它是一个带有 TableViewController 的故事板。 'self.tableView' 是一个连接到 TableView 的属性(IBOutlet UITableView)。
  • 您没有使用 indexPath 获取单元格。在情节提要中给它一个重用标识符并使​​用 MasterCell *cell = (MasterCell *)[tableView dequeueReusableCellWithIdentifier:@"masterCell"];
  • 为了清楚起见,您实际上是在尝试通过您的示例访问 first 部分中的 second 行。它是 nil 的问题可能是由于单元格不可见(如 Martin R 所述),因为您的 indexPath 超出范围(即第一部分中没有第二行你的桌子)。 developer.apple.com/library/ios/documentation/uikit/reference/…:
  • @gschandler:你说得对,索引超出范围是另一个可能的原因,我忘了提到这一点。 - 但无论如何,检索单元格“更改某些值”并不是一个好主意。

标签: ios uitableview


【解决方案1】:

[self.tableView cellForRowAtIndexPath:indexPath] 为当前不可见的单元格返回 nil

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

【讨论】:

  • 非常感谢 Darren 和 Martin R!我可以在方法'- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath'中设置初始值(它确实是一个从核心数据实体获取其值的 UIStepper)。工作正常!
  • 通过'self.tableView.subviews'访问怎么样?
猜你喜欢
  • 1970-01-01
  • 2013-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
相关资源
最近更新 更多