首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SWIFT4.2 TableViewCell动态高度的编程实现

SWIFT4.2 TableViewCell动态高度的编程实现
EN

Stack Overflow用户
提问于 2019-03-15 08:44:28
回答 3查看 9.8K关注 0票数 4

这不是重复的问题,因为这个问题没有真正的解决方案。

我正在尝试通过使用约束实现UITableViewcell动态高度的内容,但得到布局警告:

将尝试通过打破约束来恢复,在UIViewAlertForUnsatisfiableConstraints上设置一个符号断点,以便在调试器中捕捉到这一点。中列出的UIConstraintBasedLayoutDebugging类别中的UIView方法也可能有所帮助。2019-03-15 12:27:52.085475+0400 TableCellDynamicHeight31984:1295380不能同时满足约束。可能下面列表中至少有一个约束是您不想要的。尝试如下:(1)查看每个约束,并尝试找出您不期望的;(2)找到添加了不需要的约束的代码并修复它。( "“、"”)

我检查了一些线程:Dynamic tableViewCell height

Dynamic Height Issue for UITableView Cells (Swift)

Swift 3 - Custom TableViewCell dynamic height - programatically

什么是正确的解决方案,我遗漏了什么?

ViewController:

代码语言:javascript
复制
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    lazy var tableView: UITableView = {
        let table = UITableView()
        table.backgroundColor = .white
        table.translatesAutoresizingMaskIntoConstraints = false
        table.register(TableViewCell.self, forCellReuseIdentifier: "cellId")
        table.dataSource = self
        table.delegate = self
        return table
    }()


    let arr:[Int:UIColor] = [345: UIColor.random, 422: .random, 23: .random, 344: .random,200: .random,140: .random]

    var pickerDataVisitLocation = [203: "Home", 204: "Hospital", 205: "Other"]

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .red

        self.view.addSubview(tableView)
//
        tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        tableView.tableFooterView = UIView()
    }
}

extension ViewController {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! TableViewCell
        let value:UIColor = Array(arr)[indexPath.row].value
        let key = Array(arr)[indexPath.row].key

        cell.setupViews(he: CGFloat(key), color: value)
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
}

extension UIColor {
    static var random: UIColor {
        return UIColor(red: .random(in: 0...1),
                       green: .random(in: 0...1),
                       blue: .random(in: 0...1),
                       alpha: 1.0)
    }
}

TableViewCell:

代码语言:javascript
复制
    import UIKit

    class TableViewCell: UITableViewCell {


        override func awakeFromNib() {
            super.awakeFromNib()


        }

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


        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }

        func setupViews(he:CGFloat, color:UIColor) {

            let v:UIView = UIView()
            v.translatesAutoresizingMaskIntoConstraints = false
            self.addSubview(v)

            v.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
            v.backgroundColor = color
            v.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
            v.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
            v.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
            v.heightAnchor.constraint(equalToConstant: he).isActive = true
            #warning("here is constraint error conflict with bottomAnchor and heightAnchor, need correct solution")
        }

    }
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-15 12:41:32

你做错了几件事。

首先,单元格被重用(因此是dequeueReusableCell),但是每次单元格被重用时,setupViews()功能都会添加一个新的子视图

这意味着当你滚动,单元格被重用,你最终得到2,3,4.十几个子视图,都有相互冲突的约束。

addSubview()移动到单元中常见的初始化功能,因此视图只创建一次并添加一次。

这也是您应该设置约束的地方。

若要在设计应用程序时更改子视图的高度,您需要在子视图的高度约束上更改.constant

这是你修改过的代码。我已经在代码中添加了足够的注释,应该是明确的:

代码语言:javascript
复制
class HattoriTableViewCell: UITableViewCell {

    // the view to add as a subview
    let myView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    // the constraint we'll use for myView's height
    var myViewHeightConstraint: NSLayoutConstraint!

    override func awakeFromNib() {
        super.awakeFromNib()
        commonInit()
    }

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

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() -> Void {

        // add the subview
        self.addSubview(myView)

        // constrain it to all 4 sides
        myView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
        myView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        myView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        myView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

        // create the height constraint
        myViewHeightConstraint = myView.heightAnchor.constraint(equalToConstant: 1)

        // needs Priority less-than 1000 (default) to avoid breaking constraints
        myViewHeightConstraint.priority = UILayoutPriority.init(999)

        // activate it
        myViewHeightConstraint.isActive = true

    }

    func setupViews(he:CGFloat, color:UIColor) {

        // set myView's background color
        myView.backgroundColor = color

        // change myView's height constraint constant
        myViewHeightConstraint.constant = he

    }

}

class HattoriViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    lazy var tableView: UITableView = {
        let table = UITableView()
        table.backgroundColor = .white
        table.translatesAutoresizingMaskIntoConstraints = false
        table.register(HattoriTableViewCell.self, forCellReuseIdentifier: "cellId")
        table.dataSource = self
        table.delegate = self
        return table
    }()


    let arr:[Int:UIColor] = [345: UIColor.random, 422: .random, 23: .random, 344: .random,200: .random,140: .random]

    var pickerDataVisitLocation = [203: "Home", 204: "Hospital", 205: "Other"]

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .red

        self.view.addSubview(tableView)
        //
        tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        tableView.tableFooterView = UIView()

        // use a reasonable value -- such as the average of what you expect (if known)
        tableView.estimatedRowHeight = 200
    }
}

extension HattoriViewController {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! HattoriTableViewCell

        let value:UIColor = Array(arr)[indexPath.row].value
        let key = Array(arr)[indexPath.row].key

        cell.setupViews(he: CGFloat(key), color: value)

        return cell
    }

    // NOT NEEDED
//  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//      return UITableView.automaticDimension
//  }
//
//  func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
//      return UITableView.automaticDimension
//  }

}

extension UIColor {
    static var random: UIColor {
        return UIColor(red: .random(in: 0...1),
                       green: .random(in: 0...1),
                       blue: .random(in: 0...1),
                       alpha: 1.0)
    }
}
票数 6
EN

Stack Overflow用户

发布于 2019-03-15 11:52:49

在您的情况下,高度在dataSource arr中可用,因此不需要:

  1. 高度约束
  2. estimatedHeightForRowAtIndexPath

您所需要的只是返回heightForRowAtIndexPath中的实际高度,但是首先,您的dataSource arr:[Int:UIColor]是一个Dictionary,我将不依赖它的命令,让它更改为Array of Tuples

代码语言:javascript
复制
var dataSource: [(height: CGFloat, color: UIColor)] = [
    (345, .random),
    (422, .random),
    (23, .random),
    (344, .random),
    (200, .random),
    (140, .random)
]

现在使用以下UITableView代理/DataSource方法:

代码语言:javascript
复制
extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return dataSource[indexPath.row].height
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! TableViewCell
        cell.setupViews(color: dataSource[indexPath.row].color)
        return cell
    }

}

由于不需要高度约束,所以我从he方法中删除了setupViews参数。

票数 2
EN

Stack Overflow用户

发布于 2021-06-16 14:47:49

我也有同样的问题,但原因不同,我想和你分享。

我只需重写layoutSubviews()方法来添加自定义布局。

但是,我并没有在初始化器中调用layoutIfNeeded()方法来激活它们,而是只有在单元被排除队列并重用时才激活布局。

以下是我的代码供您参考,如果您面临同样的问题:

代码语言:javascript
复制
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    contentView.addSubviews(containerView)
    containerView.addSubviews(titleLabel, subtitleLabel, activteSwitch)

    layoutIfNeeded() // Required to triger the overriden layoutSubviews() upon initialization
}

// However, I shouldn't override this method or add any constraints here
override func layoutSubviews() {
    let margin: CGFloat = 8

    containerView.snapToEdges()
    NSLayoutConstraint.activate([
        activteSwitch.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -margin),
        activteSwitch.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),

        titleLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: margin),
        titleLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: margin),
        titleLabel.trailingAnchor.constraint(equalTo: activteSwitch.leadingAnchor, constant: -margin),

        subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: margin),
        subtitleLabel.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: margin),
        subtitleLabel.trailingAnchor.constraint(equalTo: activteSwitch.leadingAnchor, constant: -margin),
        subtitleLabel.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -margin)

    ])
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55178641

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档