首页 > 解决方案 > 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")
    }
}

标签: swifttableview

解决方案


let lastMsg : UILabel?是一个常数,在调用之前需要一个值super.init()

做就做let lastMsg = UILabel(),不需要的时候就不要展示,lastMsg.isHidden = true


推荐阅读