【问题标题】:custom tableviewcell dynamic height not updating as per constraints (with programmatically autolayout)自定义 tableviewcell 动态高度未根据约束更新(以编程方式自动布局)
【发布时间】:2020-02-15 17:54:01
【问题描述】:

我在应用中有一个自定义的 uitableviewcell,我正在尝试根据其子视图(标签)内容动态更新其长度。

但它不起作用。

找到相关代码如下。

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)
  ])
    }

和内部视图控制器文件:

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

在viewdidload中:

    transactionTableView.dataSource = Objdatasource 
        transactionTableView.delegate = Objdelegate

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

【问题讨论】:

    标签: ios swift uitableview autolayout


    【解决方案1】:

    删除这个

    dateLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 1.0)
    

    【讨论】:

    • 根据您的反馈,我已删除,但没有成功。 @Sh_Khan
    【解决方案2】:

    this 教程(我最近关注并为我工作)中,您缺少一个功能:

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

    【讨论】:

    • 我认为我们不需要编写上面的函数,因为我已经指定了下面的代码:tableview.rowHeight = UITableView.automaticDimension tableview.estimatedRowHeight = 300
    • 根据您的评论,我仍然具有包含功能。但它仍然没有工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2015-12-26
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多