I'm trying to create a dynamic cell where sometimes I would like the cell to show the last message and sometimes I don't want the label to be there.
I get an error saying lastMsg
not initialized at super.init
here's my cell:
class mainChatCell: UITableViewCell {
let imgUser = UIImageView()
let labUserName : UILabel = {
let lab = UILabel()
lab.text = "emily"
return lab
}()
let lastMsg : UILabel?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
imgUser.backgroundColor = UIColor.blue
imgUser.layer.cornerRadius = 25
imgUser.clipsToBounds = true
imgUser.translatesAutoresizingMaskIntoConstraints = false
labUserName.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(imgUser)
let stack = UIStackView(arrangedSubviews: [labUserName, lastMsg ?? UIView()])
stack.translatesAutoresizingMaskIntoConstraints = false
stack.axis = .vertical
stack.distribution = .fillEqually
contentView.addSubview(stack)
let consts = [
imgUser.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 15),
imgUser.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: 0),
imgUser.widthAnchor.constraint(equalToConstant: 50),
imgUser.heightAnchor.constraint(equalToConstant: 50),
stack.leadingAnchor.constraint(equalTo: imgUser.trailingAnchor, constant: 10),
stack.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
]
NSLayoutConstraint.activate(consts)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Your let lastMsg : UILabel?
is a constant and requires a value before calling super.init()
.
Just do let lastMsg = UILabel()
, and when you don't need it just don't show it, lastMsg.isHidden = true
.