【问题标题】:UILabel inside UITableViewCell - height isn't adjusting correctlyUITableViewCell 内的 UILabel - 高度未正确调整
【发布时间】:2016-06-23 02:16:10
【问题描述】:

查看粉红色UITableViewCell. 中的第二个UILabel 如您所见,其中的文本被截断。我一直在尝试让 UILabel 的高度根据插入的文本数量正确扩展或缩小 - 并且它不起作用。


• 我正在使用AutoLayouts
UILabel 的所有 4 个侧面都固定在 ContentView 上 - 当然是在 UITableViewCell 内部
• 顺便说一下,这些细胞都是Static 细胞,而不是Prototype 细胞。
• 这是我正在使用的代码:

(在视图中将出现)

descriptionLabel.text = " < a bunch of text goes here > "
descriptionLabelSize = descriptionLabel.sizeThatFits(descriptionLabel.bounds.size)
// here's a global var I use to store the height:
descriptionLabelHeight = descriptionLabelSize.height

然后,在 viewDidAppear 中(仅供参考,我还尝试将以下内容放入 willdidLayoutSubviews 以及各种其他排列中:)

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    var newFrame = descriptionLabel.frame
    newFrame.size.height = descriptionLabelHeight
    descriptionLabel.frame = newFrame

    descriptionLabel.setNeedsLayout()
    view.layoutIfNeeded()
}

最后,在heightForRowAtIndexPath我使用全局变量来调整TableViewCell的高度:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    switch indexPath.row {
    case 0: return 50
    case 1: return descriptionLabelHeight+20   // the + 20 is for padding & margin
    default: return 50
    }
}

结果好坏参半:标签的高度 - 以及容纳它的单元格 - 确实调整 - 但还不够。它总是以太短而告终。我并不是说它只是截断了几个词,它的方式太短了,截断了多个句子。
但同样:高度调整。这就是奇怪的部分。它的工作 - 还不够。

任何提示将不胜感激!

【问题讨论】:

    标签: ios uitableview uilabel height


    【解决方案1】:

    您需要告诉表格视图根据内容动态缩放单元格:

    tableView.rowHeight = UITableViewAutomaticDimension
    

    然后,您可以删除 heightForRowAtIndexPath: 的实现 - 单元格应该会自动缩放。请记住正确设置布局约束。没有它,动态大小将不起作用。

    【讨论】:

    • 好吧,我已经尝试过UITableViewAutomaticDimension,但没有成功。但让我具体一点:在viewDidLoad 中,我输入了tableView.rowHeight = UITableViewAutomaticDimension,然后我注释掉了heightForRowAtIndexPath - 所有单元格都返回相同的高度(44 分。)我应该以不同的方式做吗?
    • 顺便说一句,你能更具体地回答“记住要正确设置布局约束”吗?我在我的 Q 中描述了标签是如何设置的:它在所有 4 个面上都固定到 ContentView。这不正确吗?如果是这样,为标签设置的正确约束是什么 - 或方程中可能涉及的其他元素?
    猜你喜欢
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 2021-10-27
    • 2016-08-19
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多