简体   繁体   English

自定义 tableviewcell 动态高度未根据约束更新(以编程方式自动布局)

[英]custom tableviewcell dynamic height not updating as per constraints (with programmatically autolayout)

I have a custom uitableviewcell in app, I am trying to update its length dynamically based on its subviews (labels) contents.我在应用程序中有一个自定义的 uitableviewcell,我试图根据其子视图(标签)内容动态更新其长度。

but it's not working.但它不起作用。

find related code as below.找到相关代码如下。

class TransactionTableViewCell: UITableViewCell{


    private lazy var dateLabel: UILabel = {
        let datelabel = UILabel()
        datelabel.textColor = .label
        datelabel.backgroundColor = .red
        datelabel.lineBreakMode = .byTruncatingTail
        datelabel.numberOfLines = 0
        datelabel.translatesAutoresizingMaskIntoConstraints = false
        return datelabel
    }()

another method in same class:

 func setupDefaultUI(){
        self.contentView.addSubview(dateLabel)
}

 override func awakeFromNib() {
        super.awakeFromNib()
        setupDefaultUI()
        buildConstraints()
    }

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

 func buildConstraints(){

        let marginGuide = self.contentView

        NSLayoutConstraint.activate([
            dateLabel.topAnchor.constraint(equalTo: marginGuide.topAnchor)
            ,
            dateLabel.leadingAnchor.constraint(equalTo: marginGuide.leadingAnchor),
            dateLabel.trailingAnchor.constraint(equalTo: marginGuide.trailingAnchor),
            dateLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 1.0)
            ,

            dateLabel.bottomAnchor.constraint(equalTo: marginGuide.bottomAnchor)
  ])
    }

and inside viewcontroller file:和内部视图控制器文件:

 private lazy var transactionTableView: UITableView = {
        let tableview = UITableView.init()
        tableview.backgroundView = nil
        tableview.backgroundColor = .clear
        tableview.rowHeight = UITableView.automaticDimension
        tableview.estimatedRowHeight = 300
        return tableview
    }()

and in viewdidload:并在 viewdidload 中:

    transactionTableView.dataSource = Objdatasource 
        transactionTableView.delegate = Objdelegate

        transactionTableView.register(TransactionTableViewCell.self, forCellReuseIdentifier: CellIdentifiers.transactionCell)

在此处输入图片说明

删除这个

dateLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 1.0)

In this tutorial (which I recently followed and worked for me), there is a function you are missing there:教程(我最近关注并为我工作)中,您缺少一个函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM