【问题标题】:How to set cell and label height according to text in tableview Swift?如何根据tableview Swift中的文本设置单元格和标签高度?
【发布时间】:2020-07-06 20:59:56
【问题描述】:

我正在制作聊天应用程序,这里如何根据来自文本字段的文本设置标签和单元格高度。

如何设置初始单元格高度 = 50,然后应相应地更改文本字段中的文本高度。

但最初我得到的是小细胞,为什么?

我给了标签的限制

leading = 100, trailing to imageview = 10, top = 0, bottom = lessthenorequalto 0

图像约束:

top = 20 height, width = 50 trailing = 20

这是代码:

   override func viewDidLoad() {
    super.viewDidLoad()

   tableView.register(UINib(nibName: "ReceiverChatTableViewCell", bundle: nil), forCellReuseIdentifier: "ReceiverChatTableViewCell")
   tableView.register(UINib(nibName: "ReceiverChatTableViewCell1", bundle: nil), forCellReuseIdentifier: "Cell")

    self.tableView.estimatedRowHeight = 80
    self.tableView.rowHeight = UITableView.automaticDimension
    //tableView.reloadData()

    }

【问题讨论】:

标签: swift uitableview label height cell


【解决方案1】:

当您使用 UITableView.automaticDimension 时,您需要设置标签的顶部和底部约束。如果您使用 equalTo 设置它,每次单元格保持该值不变。当您的标签有单行标签高度+(顶部,底部填充)小于您的图像高度。这就是图像裁剪的原因你的情况。

使用lessThanOrEqualTo 而不是使用equalTo 作为标签底部约束。

addSubview(lblMessage)
addSubview(img)

img.translatesAutoresizingMaskIntoConstraints = false
img.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
img.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16).isActive = true
img.widthAnchor.constraint(equalToConstant: 50).isActive = true
img.heightAnchor.constraint(lessThanOrEqualToConstant: 50).isActive = true

lblMessage.translatesAutoresizingMaskIntoConstraints = false
lblMessage.leadingAnchor.constraint(equalTo: leadingAnchor,constant: 16).isActive = true
lblMessage.trailingAnchor.constraint(equalTo: img.leadingAnchor, constant: -16).isActive = true
lblMessage.topAnchor.constraint(equalTo: topAnchor,constant: 16).isActive = true
lblMessage.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: -16).isActive = true

【讨论】:

  • 谢谢你,它适用于单行文本,如果我输入长文本,那么单元格高度现在不会增加
  • 我犯了一个错误。您还需要将lessThanOrEqualToConstant 添加到图像视图高度。我更新代码。
  • 我给故事板约束和你一样.. 但没有得到,我可以使用 github 分享我的代码.. 它非常小的项目.. 你可以在几分钟内解决它.. 但我在这里更新鲜
  • 谢谢你,请检查一下这里的代码,你可以在storyboard和xib cell中找到约束..github.com/SwiftSamples/CellHeightIssue
  • 问题是您将标签和图像视图添加到另一个视图。所以将lessThanOrEqualToConstant 添加到这些视图而不是标签和图像视图
猜你喜欢
  • 2013-07-25
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
相关资源
最近更新 更多