【问题标题】:UITableViewCell rowHeight with UITableViewAutomaticDimension doesn't work with compute autoLayout带有 UITableViewAutomaticDimension 的 UITableViewCell rowHeight 不适用于计算 autoLayout
【发布时间】:2018-06-12 17:58:44
【问题描述】:

我有多个组件作为行的 UITableViewCell,由 UIView 内的 UILabel、UIView 和 UIStackView 的混合元素组成。

单元格内的每个组件都有高度限制。我希望单元格的高度是动态的,方法是在运行时将高度约束的常数设置为零或 21,取决于它是否有要显示的内容。

// more codes like below    
if let mealPref = passenger.mealPref {
    mealPrefHeight.constant = 21
    let title = R.string.localizable.meal_request.localized()
    mealPrefLabel.text = "• \(title): \(mealPref)"
} else {
    mealPrefHeight.constant = 0
}
// more codes like above

它不起作用。

我有类似的problem back then,但我认为情况不同。我读过thisthisthis

【问题讨论】:

  • 如果您在运行时更改约束的constant AutomaticDimension 将不起作用。如果设置常量 = 21,则自动尺寸将被覆盖。

标签: ios iphone swift uitableview uiview


【解决方案1】:

你加了viewDidLoad

tableView.estimatedRowHeight = 44 // for assumption
tableView.rowHeight = UITableViewAutomaticDimension

【讨论】:

  • 我在 heightForRow 部分添加了 UITableViewAutomaticDimension。将尝试添加您的代码。
  • 这就是解决方案。我需要同时设置tableView.estimatedRowHeighttableView.rowHeight 作为您的答案。 +1,我接受你的回答。
  • 谢谢,很高兴为您提供帮助
【解决方案2】:

尝试移除高度限制。

if let mealPref = passenger.mealPref {
   let title = R.string.localizable.meal_request.localized()
   mealPrefLabel.text = "• \(title): \(mealPref)"
 }  

【讨论】:

    【解决方案3】:

    您可以在UITableViewDelegate 方法中简单地更改UITableViewCell's 的高度:

    可选的 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

    示例:

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        if indexPath.row == 0
        {
            return 126.0
        }
        else
        {
            return 90.0
        }
    }
    

    您可以根据需要更改高度。这里我只是使用了行号来改变高度。

    截图:

    【讨论】:

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