【问题标题】:How to change tableview cell height according to label text swift?如何根据标签文本快速更改表格视图单元格高度?
【发布时间】:2017-09-20 10:24:10
【问题描述】:

Swift 中使用 UITableView,有人可以帮我根据标签、图片和描述自动更改单元格的高度吗?

我想随着标签文本的增加动态更改单元格大小。我已经在标签上应用了自动布局。

【问题讨论】:

  • 可以添加表格视图单元格约束的图像吗?
  • 您必须像这样设置标签:yourLabel.numberOfLines = 0; yourLabel.lineBreakMode = .byWordWrapping。另一种可能是在标签上设置宽度约束,然后添加文字,然后调用yourLabel.sizeToFit()

标签: swift uitableview autolayout


【解决方案1】:

考虑到您已经在标签上应用了约束。并将您的行数设置为 0。然后将以下代码粘贴到 viewDidLoad 方法中

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension

【讨论】:

  • 在这种情况下,标签是否应该定义bottomAnchor?
【解决方案2】:

如果下面的代码在方法 viewDidLoad 中不起作用,请在方法中添加下面的代码 ViewWillAppear

tableView.estimatedRowHeight = 60.0// the estimated row height ..the closer the better
tableView.rowHeight = UITableView.automaticDimension

加号:

  1. 约束应至少定义宽度、顶部间距和底部间距而不是高度约束
  2. 在属性中将行设置为 0

【讨论】:

    【解决方案3】:

    要使单元格自动变大,您需要做两件事:

    1. 底部空间和顶部空间限制将根据需要推动单元格大小。标签行数为0。

    2. 在你的 viewDidLoad() 方法中添加self.tblList.estimatedRowHeight = 50.0 self.tblList.rowHeight = UITableViewAutomaticDimension

    【讨论】:

      【解决方案4】:

      Swift 4 答案:

      tableView.estimatedRowHeight = 44.0
      tableView.rowHeight = UITableView.automaticDimension
      

      请确保已设置约束

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多