我遇到了创建超类然后在子类中重写它的问题。我仍然是iOS和swift的初学者,所以如果我的解释和措辞错误,我会提前道歉。请参阅下面的代码我正在使用:
// created super class in .swiftfile A
class BaseCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
func setupViews() {
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// swiftfile B trying to call the superclass
class MenuBar: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = UIColor.rgb(230, green: 32, blue: 31)
cv.dataSource = self
cv.delegate = self
return cv
}()
let cellId = "cellId"
override init(frame: CGRect) {
super.init(frame: frame)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
addSubview(collectionView)
addConstraintsWithFormat("H:|[v0]|", views: collectionView)
addConstraintsWithFormat("V:|[v0]|", views: collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell (withReuseIdentifier: cellId, for: indexPath)
// ** when I uncomment this the blue cells show up cell.backgroundColor = UIColor.blue
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: frame.width / 4, height: frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//subclass I am trying to call super class into
class MenuCell: BaseCell {
override func setupViews() {
super.setupViews()
// *** but when I run the app these yellow cells do not show
backgroundColor = UIColor.yellow
}
}
答案 0 :(得分:0)
在cellForItemAt
方法中,您不是将单元格转换为自定义类
guard let cell = collectionView.dequeueReusableCell (withReuseIdentifier: cellId, for: indexPath) as? BaseCell else {
return UICollectionViewCell()
}
Hamish 还指出您没有注册自定义单元格