【问题标题】:UItableView automaticDimension not working with UIStackViewUItableView automaticDimension 不适用于 UIStackView
【发布时间】:2021-03-08 06:30:02
【问题描述】:

我希望我的UITableViewCell 正确计算其高度,使其底部与UIStackView 底部匹配。

我知道要使UITableView.automaticDimension 工作,您需要设置UITableViewCell 的所有垂直约束,以便它可以计算其高度。

这就是我做不到的。我做了一个测试项目,我确定:

  • tableView.rowHeight 属性设置为 UITableView.automaticDimension
  • 不实现函数heightForRowAt
  • TableViewCell Row Height 在 xib 文件中设置为 Automatic
  • 所有视图都受到垂直约束。
  • UIStackViewdistribution属性。
  • 要将UIStackView 底部约束设置为superViewLess Than or Equal(此项目太小并且Greater Than or EqualEqual,项目的高度等于屏幕宽度,因为它们有@987654344 @ 1:1
  • Content Hugging PriorityContent Compression Resistance Priority 一起玩。在测试中,所有视图都有默认值,水平和垂直拥抱为 250,水平和垂直压缩为 750。

代码:

import Foundation
import UIKit

class IBAutomaticDimensionTableViewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource  {
    
    @IBOutlet private weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(
            IBAutomaticDimensionTableViewCell.nib,
            forCellReuseIdentifier: IBAutomaticDimensionTableViewCell.nibName
        )
        tableView.delegate = self
        tableView.dataSource = self
        tableView.reloadData()
//        view.layoutIfNeeded() Not working with or without it
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(
            withIdentifier: IBAutomaticDimensionTableViewCell.nibName,
            for: indexPath
        ) as! IBAutomaticDimensionTableViewCell
        return cell
    }
}

单元格的 xib 文件:

Less Than or Equal 底部约束的结果:

带有Greater Than or EqualEqual 底部约束的结果:

【问题讨论】:

    标签: swift uitableview storyboard uistackview uitableviewautomaticdimension


    【解决方案1】:

    问题在于纵横比限制。似乎他们优先考虑宽度而不是高度(这对我来说很奇怪,因为高度是一个常数值,我希望它优先于计算出来的值,但 Apple 的想法不同)

    在Android中你可以指定哪个有偏好(宽度或高度),我不知道这里有什么方法(玩纵横比约束的关系没有解决它)

    替换硬编码宽度值的纵横比约束(第一个视图为 32,其余为 20)解决了这个问题

    【讨论】:

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