UITableView自动尺寸不起作用:UIView-Encapsulated-Layout-Height错误

问题描述 投票:0回答:1

我正在尝试实现自定义表格视图单元格。我在单元格内设置了自动布局高度,但显示了自动布局错误。

我设置了translatesAutoresizingMaskIntoConstraints = false并设置了UITableView.autoDimension。

它显示如下自动布局错误。

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x6000024ce9e0 DisposeSecond.MyCell:0x7f9ba7104aa0'cell'.height == 100   (active)>",
    "<NSLayoutConstraint:0x6000024ce800 'UIView-Encapsulated-Layout-Height' DisposeSecond.MyCell:0x7f9ba7104aa0'cell'.height == 100.333   (active)>"
)

我的实现非常简单。


import UIKit

class MyCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        translatesAutoresizingMaskIntoConstraints = false
        self.heightAnchor.constraint(equalToConstant: 100).isActive = true

        // Set debug colors to visualize heigh
        layer.borderWidth = 2
        layer.borderColor = UIColor.blue.cgColor
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class MyTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(MyCell.self, forCellReuseIdentifier: "cell")
    }


    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 30
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyCell
        return cell
    }

    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // I know it is set automatically but just indeed
        return UITableView.automaticDimension
    }
}

swift uitableview autolayout uikit
1个回答
0
投票
UITableView.automaticDimension

这会强制tableviewCell根据应用于单元格的约束来计算其高度。然后在您的单元格中,您编写了以下代码:

self.heightAnchor.constraint(equalToConstant: 100).isActive = true

还将在单元格上应用高度限制。

这两个有冲突,要么删除上面的行,要么更改tableview的大小委托

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 100
}
© www.soinside.com 2019 - 2024. All rights reserved.