【问题标题】:Set the colour of all the labels in tableview设置tableview中所有标签的颜色
【发布时间】:2020-06-03 18:44:55
【问题描述】:

如何使用 swift 设置表格视图部分中每个标签的颜色?

我已经这样做了,但它不起作用。

谢谢

    for section in 0..<tableView.numberOfSections {
        for row in 0..<tableView.numberOfRows(inSection: section) {
            let indexPath = NSIndexPath(row: row, section: section)
            var cell = tableView.cellForRow(at: indexPath as IndexPath)

            if (cell as? UILabel) != nil {
                cell?.textLabel?.textColor = .red

            }
        }

    }

【问题讨论】:

  • 你为什么要这样做?
  • 单元格是否总是应该是红色的,还是由于其他操作而变为红色?
  • 你能告诉我们你的 tableview 代表吗?单元格在委托中创建/回收/自定义。
  • 这不起作用,因为无法将单元格强制转换为 UILabel。无论如何,直接操作单元格(甚至是不可见的单元格)都是不好的做法。

标签: swift tableview sections


【解决方案1】:

您应该在cellForRowAt 方法中设置单元格的属性,如下所示:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: <#T##String#>, for: indexPath)
    cell.textLabel?.backgroundColor = .red
    return cell
}

【讨论】:

    【解决方案2】:

    您正在与类型发生冲突。 在这一行中,您将单元格类型分配给变量单元格

    var cell = tableView.cellForRow(at: indexPath as IndexPath)
    

    在这行代码中,您询问单元格是否为 UILabel,然后将其文本标签颜色设置为红色。

    这将始终返回 false 并且内部的代码永远不会执行。

                if (cell as? UILabel) != nil {
                    cell?.textLabel?.textColor = .red
    
                }
    

    删除 if 语句,然后执行代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-05
      • 2018-01-23
      • 2015-04-22
      • 2015-09-04
      • 2017-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多