Reputation: 7613
I have a custom uitableviewcell in app, I am trying to update its length dynamically based on its subviews (labels) contents.
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:
transactionTableView.dataSource = Objdatasource
transactionTableView.delegate = Objdelegate
transactionTableView.register(TransactionTableViewCell.self, forCellReuseIdentifier: CellIdentifiers.transactionCell)
Upvotes: 0
Views: 44
Reputation: 19
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
}
Upvotes: 0
Reputation: 100503
Remove this
dateLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 1.0)
Upvotes: 1