【问题标题】:UITableViewCell height auto layout not working on iOS 10UITableViewCell 高度自动布局在 iOS 10 上不起作用
【发布时间】:2018-05-24 15:38:12
【问题描述】:

我有一个非常简单的UITableViewController,我想在UITableViewCells 的每个textLabel 上设置一个文本。

高度应通过自动布局计算。因此,在我的viewDidLoad 中将以下值设置为tableView 属性:

tableView.estimatedRowHeight = UITableViewAutomaticDimension
tableView.rowHeight = UITableViewAutomaticDimension

这是我的cellForRow 方法,我在其中初始化默认的UITableViewCell 并将文本设置为其标签。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.numberOfLines = 0
        cell.textLabel?.text = "hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello"
        return cell
    }

我的问题是,单元格不会根据标签的大小增长。此问题仅出现在 iOS 10 上。在 iOS 11 上,一切都按原样布置。

请查看以下截图:

  • iOS 10

  • iOS 11

编辑:2018 年 5 月 24 日

只有textLabel,如果estimatedRowHeight 上有实际值,它将起作用。

但是有一个样式为.subtitle 的单元格,并将值设置为descriptionLabel,布局将不起作用。同样的问题:iOS 10 不工作。 iOS 11 有效(单元格根据两个标签调整大小)。

【问题讨论】:

    标签: swift uitableview uikit


    【解决方案1】:

    此配置来自您的viewDidLoad:

    tableView.estimatedRowHeight = UITableViewAutomaticDimension
    tableView.rowHeight = UITableViewAutomaticDimension
    

    ...仅适用于 iOS 11。它是 iOS 11 的一项创新,不适用于早期系统。

    对于 iOS 10,您必须提供实际的 estimatedRowHeight 值(例如 60)才能启用自动可变行高计算。

    【讨论】:

    • 这解决了这个问题。但如果单元格也使用descriptionLabel,则不会在 iOS 10 上运行。我相应地更新了我的问题。
    • @kchromik 最简单的解决方案是:不要使用内置的.subtitle 样式。它不适用于自行调整大小的单元格,因此它不能以向后兼容的方式工作。只需制作带有两个标签的自定义单元格类型。这将适用于 iOS 10 和 iOS 11。
    • 很高兴知道,我认为它会开箱即用。届时将建立我自己的细胞,谢谢你的帮助。
    • iOS10 中的可变高度固定问题。你拯救了我的一天。非常感谢。
    • 这有帮助。我已经挣扎了将近 16 个小时,不知道如何解决这个问题。很奇怪,不明白为什么这是 iOS 10 的第一手问题。
    猜你喜欢
    • 2013-10-21
    • 2014-01-03
    • 2019-11-30
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多