要实现 UITableView Cell 的自适应高度,可以按照以下步骤进行操作:

  1. 在 UITableView 的代理方法 'tableView:heightForRowAtIndexPath:' 中返回自适应的高度。
  2. 在 UITableView 的代理方法 'tableView:cellForRowAtIndexPath:' 中根据数据计算出 Cell 的高度,并返回正确的 Cell。
  3. 在 UITableViewCell 的子类中重写 'layoutSubviews' 方法,根据子视图的大小调整 Cell 的高度,并使用 Auto Layout 或者设置子视图的 'translatesAutoresizingMaskIntoConstraints' 属性为 'false',以支持自动调整视图大小。

下面是一个示例代码,演示如何实现 UITableView Cell 的自适应高度:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    var data = ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sed diam eget risus varius blandit sit amet non magna.',
                'Vestibulum id ligula porta felis euismod semper. Nulla vitae elit libero, a pharetra augue.',
                'Curabitur blandit tempus porttitor. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.']
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.estimatedRowHeight = 100 // 设置一个估计的行高
        tableView.rowHeight = UITableView.automaticDimension // 设置行高为自动调整
    }
    
    // MARK: - UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: 'Cell', for: indexPath) as! MyTableViewCell
        cell.titleLabel.text = data[indexPath.row]
        return cell
    }
    
    // MARK: - UITableViewDelegate
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension // 返回自动调整的行高
    }
}

class MyTableViewCell: UITableViewCell {
    
    @IBOutlet weak var titleLabel: UILabel!
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 调整子视图的大小和位置
        titleLabel.preferredMaxLayoutWidth = titleLabel.frame.width
    }
}

在上面的例子中,我们首先在 'viewDidLoad' 方法中设置了 UITableView 的 'estimatedRowHeight' 和 'rowHeight' 属性,使其支持自适应高度。

然后,在 'tableView:cellForRowAtIndexPath:' 方法中,我们将数据赋值给 UITableViewCell 的子视图 titleLabel,并返回正确的 Cell。

最后,在 UITableViewCell 的子类 MyTableViewCell 中重写了 'layoutSubviews' 方法,调整了 titleLabel 的大小和位置。

这样,当 UITableView 显示时,Cell 的高度会根据 titleLabel 的内容自动调整。

iOS UITableView Cell 自适应高度实现指南

原文地址: https://www.cveoy.top/t/topic/qfY3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录