【问题标题】:Create Auto-sizing TableView programmatically以编程方式创建自动调整大小的 TableView
【发布时间】:2018-06-01 10:24:57
【问题描述】:

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

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
}

【问题讨论】:

    标签: swift uitableview autolayout


    【解决方案1】:

    你也应该添加底部约束

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

    【讨论】:

    • 我希望表格单元格以及标题L 设置自己的固有高度
    • 标签将设置自己的固有高度。对于自动单元格高度,您应该在所有四个侧面为其子视图添加约束。
    猜你喜欢
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    相关资源
    最近更新 更多