当我用范围声明集合视图时,它不会注册单元类
lazy var flowLayout:UICollectionViewFlowLayout = {
let f = UICollectionViewFlowLayout()
f.scrollDirection = .horizontal
f.itemSize = CGSize(width: 100, height: 100)
f.minimumInteritemSpacing = CGFloat.greatestFiniteMagnitude
f.minimumLineSpacing = 5
return f
}()
lazy var collection: UICollectionView = {
let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.flowLayout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.showsVerticalScrollIndicator = false
cv.showsHorizontalScrollIndicator = false
cv.dataSource = self
cv.delegate = self
cv.register(PreviewFilmsPosterCell.self, forCellWithReuseIdentifier: cellId)
cv.backgroundColor = .black
return cv
}()
会抛出此错误:
由于未捕获的异常而终止应用 'NSInternalInconsistencyException',原因:'尝试注册一个 cell类,它不是UICollectionViewCell的子类
什么是正确的解决方案?
更新
但如果我这样声明它可以正常工作
override func viewDidLoad() {
collectionview = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
collectionview.translatesAutoresizingMaskIntoConstraints = false
collectionview.dataSource = self
collectionview.delegate = self
collectionview.register(PreviewFilmsPosterCell.self, forCellWithReuseIdentifier: cellId)
collectionview.showsVerticalScrollIndicator = false
collectionview.showsHorizontalScrollIndicator = false
collectionview.backgroundColor = .black
}
我的 PreviewFilmsPosterCell类
class PreviewFilmsPosterCell: UICollectionViewCell {
let profileImageButton: UIButton = {
let button = UIButton()
button.layer.cornerRadius = 50
button.clipsToBounds = true
button.setImage(UIImage(named: "profile_batman"), for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override init(frame: CGRect) {
super.init(frame: frame)
addViews()
}
func addViews(){
backgroundColor = UIColor.clear
addSubview(profileImageButton)
profileImageButton.heightAnchor.constraint(equalToConstant: 100).isActive = true
profileImageButton.widthAnchor.constraint(equalToConstant: 100).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
答案 0 :(得分:0)
PreviewFilmsPosterCell
NOT 是UICollectionViewCell的子类。
它必须继承要在UICollectionView
中使用的UICollectionViewCell确保您的单元格正确继承
class PreviewFilmsPosterCell: UICollectionViewCell {...}
答案 1 :(得分:0)
问题出在这里
cv.register(PreviewFilmsPosterCell.self, forCellWithReuseIdentifier: cellId)
此PreviewFilmsPosterCell
类不是UICollectionViewCell的子类
一定是
class PreviewFilmsPosterCell:UICollectionViewCell
答案 2 :(得分:0)
我在Date