1
我遇到了創建超類,然後在子類中重寫它的問題。我在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
}
}
您註冊的單元類類型爲'UICollectionViewCell.self'而不是'MenuCell.self' ... – Hamish
謝謝!解決了它 – user3708224