我目前正在像这样以编程方式创建我的 UITableViewCells:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Home-Cell" forIndexPath:indexPath];
UILabel *newLabel = [[UILabel alloc] initwithframe:cell.frame];
[newLabel setText:self.data[indexPath.row]];
[cell addSubview:newLabel];
return cell;
}
虽然每次重复使用单元格时,这似乎都会创建一个新的 UILabel,但我绝对不希望这样。我尝试执行以下操作:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Home-Cell" forIndexPath:indexPath];
if (cell == nil) {
UILabel *newLabel = [[UILabel alloc] initwithframe:cell.frame];
[cell addSubview:newLabel];
}
[newLabel setText:self.data[indexPath.row]];
return cell;
}
但是 UILabel 似乎永远不会被创建。也许这是因为我将原型(prototype)单元与 Storyboard 一起使用,因此单元永远不会为零?
最佳答案
你有两个解决方案。
- 创建一个已有标签的自定义表格 View 单元格。
- 如果您想在代码中添加标签,请不要为单元格注册类。然后出队的单元格可以是
nil
并且您可以在那个时候添加标签(就像在您的第二组代码中一样)。这还需要使用dequeueReusableCellWithIdentifier
方法,该方法也不需要indexPath
。
关于ios - UILabel 在 UITableViewCell 中多次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32728213/