ios - UILabel 在 UITableViewCell 中多次出现

标签 ios objective-c uitableview

我目前正在像这样以编程方式创建我的 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 一起使用,因此单元永远不会为零?

最佳答案

你有两个解决方案。

  1. 创建一个已有标签的自定义表格 View 单元格。
  2. 如果您想在代码中添加标签,请不要为单元格注册类。然后出队的单元格可以是 nil 并且您可以在那个时候添加标签(就像在您的第二组代码中一样)。这还需要使用 dequeueReusableCellWithIdentifier 方法,该方法也不需要 indexPath

关于ios - UILabel 在 UITableViewCell 中多次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32728213/

相关文章:

ios - 苹果指南 14.3, "ability to block abusive users "

ios - UICollectionView 和自动布局

ios - 如何向 uiviewcontroller 添加圆角半径

objective-c - 将 NSURLConnecion 委托(delegate)与 NSURLConnection +sendAsynchronousRequest 一起使用

javascript - 用户界面自动化: Access UIViews inside UIScrollView

iphone - 来自 pList 的 UITableView 分段,可以深入到 subview

json - 在TableView上执行搜索后,应用程序崩溃

ios - 无法使用类型 'String' 的参数列表调用类型 '(RemoteConfigValue)' 的初始值设定项

ios - OS X 中的accessibilityElementsHidden?如何保护我的应用程序的 UI 内部结构不被窃取?

ios - 我怎么知道 UItableview 中 Cell 的按钮被点击了