我有一个 UITableViewCell
,它是通过包含 UITextField
和 UILabel
的 Storyboard 设计的。我想在调用 cellForRowAtIndexPath
时更新这些 View 的值。
我首先尝试像这样获取对文本字段和标签的引用:
UITextField *textfield = (UITextField*)[cell.contentView viewWithTag:10];
UILabel *label = (UILabel*)[cell.contentView viewWithTag:20];
这适用于 UILabel
,但我只能在第一次创建单元格时获得对 UITextField
的引用,我能够设置原始值(textField.text
) 但从不更新它。如果我检查 subview 数组,我可以看到 UITextField
在那里,我只是无法使用 viewWithTag
访问它。我切换到这个(下面)并且它有效:
UITextField* textField = [[cell.contentView subviews] objectAtIndex:0];
UILabel *label = [[cell.contentView subviews] objectAtIndex:1];
为什么第一种方法不起作用?执行此操作的正确方法是什么?
此代码在以下上下文中:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*) indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailCell" forIndexPath:indexPath];
UITextField* textField = [[cell.contentView subviews] objectAtIndex:0];
textField.text = @"<something>";
UILabel *label = [[cell.contentView subviews] objectAtIndex:1];
label.text = @"<something else>";
return cell;
}
最佳答案
对不起。这只是我这边的一个错误,我很抱歉浪费你的时间。我覆盖了 Storyboard UI 中设置的 textField.tag 的值。 (我依赖它是 Storyboard 中设置的值,但事实并非如此)。原始代码运行正确。仍然不确定哪种方法更好。假定特定索引或特定标记值是否更安全?这些对我来说都不安全。
关于iphone - 获取 UITableViewCell 的 subview (UITextField 或 UILabel)——两种方式,一种有效,一种无效——为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18879326/