swift - 以编程方式创建自动调整大小的 TableView

标签 swift uitableview autolayout

我正在尝试以编程方式创建一个自动调整大小的表格 View ,但单元格没有增加它们的高度以适应内容,因此下一个单元格从前一个单元格开始。请问我还需要做什么吗?

MyTableViewControler.swift

override func viewDidLoad() {

        super.viewDidLoad()

        tableView.estimatedRowHeight = 120
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.translatesAutoresizingMaskIntoConstraints = false
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)

        if (cell == nil) {

            cell = UITableViewCell.init(style: .default, reuseIdentifier: reuseIdentifier)
            cell?.translatesAutoresizingMaskIntoConstraints = false

            let contentView = (cell?.contentView)!

            // Title
            let titleL = UILabel(frame: .zero)
            contentView.addSubview(titleL)

            titleL.translatesAutoresizingMaskIntoConstraints = false
            titleL.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
            titleL.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: 0).isActive = true
            titleL.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 0).isActive = true
        }

        return cell
}

enter image description here

最佳答案

你还应该添加底部约束

    titleL.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0).isActive = true

关于swift - 以编程方式创建自动调整大小的 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50641368/

相关文章:

swift - 符合具有通用约束的协议(protocol)的弱属性

ios - 解析 JSON 数组的问题

uitableview - 使用 Swift 3.0 中的数据在 Xib 中显示 tableView

iphone - 让 UITableView 不在 UIScrollView 中滚动和增长

swift - iOS14 中表格部分标题中的白色背景

swift - RxSwift 数组中的可观察值序列

ios - heightForImageCellAtIndexPath 中 dispatch_once 的原因

swift - 如何在单元格之间获得更均匀的垂直距离?

ios - 自动布局和 UIScrollView

ios - Swift 中的 UITextField `setText`