问题描述
我有一个如下所示的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
}
}
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版本?任何帮助将不胜感激。
解决方法
忘记设置数据源和委托!