0

我有一个 UITableViewCell 的自定义子类,如下所示

class GroupSelectionTableViewCell: UITableViewCell {

    // MARK: - Properties
    
    var groupSelectionLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.backgroundColor = .clear
        label.font = UIFont.systemFont(ofSize: 18)
        return label
    }()
    
    var groupSelectionImageView: UIImageView = {
        let iv = UIImageView()
        iv.backgroundColor = .clear
        iv.setHeight(height: 25)
        iv.setWidth(width: 25)
        iv.contentMode = .scaleAspectFill
        return iv
    }()

    // MARK: - LifeCycle
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

         configureUI()
     }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Helper Functions
    private func configureUI() {
        
        self.addSubview(groupSelectionLabel)
        groupSelectionLabel.centerY(inView: self)
        groupSelectionLabel.anchor(left: self.leftAnchor, paddingLeft: 12)
        
        self.addSubview(groupSelectionImageView)
        groupSelectionImageView.centerY(inView: self)
        groupSelectionImageView.anchor(right: self.rightAnchor, paddingRight: 12)
        
        self.backgroundColor = .black
        self.selectionStyle = .none
    }
}

以及如下所示的 UITableView 的自定义子类...

class GroupSelectionView: UITableView {
    
    // MARK: - Properties
    
    private let cellID = "GroupSelectionTableViewCell"

    override init(frame: CGRect, style: UITableView.Style) {
        super.init(frame: frame, style: style)
        
        backgroundColor = .red
        setHeight(height: 450)
        setWidth(width: 300)
        register(GroupSelectionTableViewCell.self, forCellReuseIdentifier: cellID)
        rowHeight = 60
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension GroupSelectionView: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        return
    }
}

extension GroupSelectionView: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        6
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! GroupSelectionTableViewCell
        cell.groupSelectionLabel.text = "None"
        cell.groupSelectionImageView.image = UIImage(named: "Tick")
        
        return cell
    }
}

但是,当我将表视图实例作为子视图添加到 UIView() 时,表视图单元格类没有运行其初始化程序。我是否正确使用了注册方法?我已经尝试实例化表视图子类并将打印语句放在表视图单元子类的初始化程序中,但它没有被打印。我是否忘记在表格视图子类上设置一些属性?我需要改用 Nib 版本的 register 吗?任何帮助将不胜感激。

4

1 回答 1

1

忘记设置数据源和委托!

于 2020-09-15T17:25:04.660 回答