swift - not initialised at super.init swift
问题描述
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")
}
}
解决方案
你let lastMsg : UILabel?
是一个常数,在调用之前需要一个值super.init()
。
做就做let lastMsg = UILabel()
,不需要的时候就不要展示,lastMsg.isHidden = true
。
推荐阅读
- typescript - Typescript - (process.env.PORT - 100 ) 编译时错误
- c++ - 指向函数的智能指针变量
- java - 如果我使用手机,是否可以导航到 Vaadin 中的另一个页面?
- spring-boot - 作业参数未注入,skiplistener 在 spring 批处理中不工作
- vue.js - 请告诉我如何消除每次更改道具时被覆盖的错误
- node.js - 代码 ELIFECYCLE npm local pacakges 不工作
- node.js - 使用 Firebase Fucntions (Node) 从存储中获取图像下载 url
- c# - 在c#中使用国家名称、日期时间和时区偏移值获取ZoneId
- python - /shop/checkout/ 处的 ValueError 不正确的 AES 密钥长度(22 字节)
- r - 在 R 中使用 Mutate_at() 更改列数据类型