首先,请不要告诉我这是重复的。我知道这个问题已经被多次询问和回答,但即使在阅读其他人的解决方案之后,我仍然无法让我的代码正常工作。UITableViewCell与UILabel子视图缓存问题
我遇到了一个包含UILabel子视图的UITableViewCell问题。 UILabel有时不会出现在某些单元格中,直到我从这些单元格滚动并返回给它们。下面是我使用自定义细胞代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *label;
if (cell == nil) {
// cell is nil, create it
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 33)];
label.tag = 888;
} else {
label = (UILabel*)[cell.contentView viewWithTag:888];
[label removeFromSuperview];
}
label.text = @"Label Text";
label.backgroundColor = [UIColor clearColor];
[label sizeToFit];
label.center = CGPointMake(cell.contentView.frame.size.width-label.frame.size.width/2-20, cell.contentView.frame.size.height/2);
[cell.contentView addSubview:label];
// customize cell text label
cell.textLabel.text = @"Cell Text";
cell.textLabel.textColor = [UIColor darkGrayColor];
return cell;
}
看来好像标签正确地显示出来时dequeueReusableCellWithIdentifier:CellIdentifier返回非零值,但不露面,如果返回值是零和一新单元必须实例化。
如果有人有一个想法,为什么这可能会发生,帮助将不胜感激。
嗨,我不明白你为什么要创建新的标签,并插入它们。基本的方法是在编辑器或代码中准备一个单元格并重用它。虽然重用意味着干净和格式化,但不会重新排列甚至找到的单元格。所以对我来说,你似乎在浪费资源。我建议你在编辑板中准备一个自定义单元格,并将其分配给一个类并重用。或者您是否有重新安排标签的具体原因? – iOS 2012-07-19 21:27:27
我不知道我明白你在说什么。我正在尝试向表格单元格的最右侧添加一个标签(与单元格的textLabel属性分开),并且标签文本可能会在每次出现表格视图时更改。 – stackunderflow 2012-07-19 22:12:13