我想显示一个在点击按钮后出现动画的 collectionView。
collectionView 显示正确,但里面的 collectionViewCells 没有。
我已经正确设置了 UICollectionViewDelegate 和 UICollectionViewDatasource 方法,但它们没有被调用(用断点测试)。
我什么都做以编程方式 所以我还必须注册 SettingCell
这是相应 cellID 的常见 UICollectionViewCell。
另外我认为可能存在问题,因为我设置委托(delegate)和数据源为时已晚,但我不这么认为,因为它们是在母类的 init 开始时设置的。
class SettingsLauncer : NSObject, UICollectionViewDelegate, UICollectionViewDataSource{
var collectionView : UICollectionView = {
let layout = UICollectionViewLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .white
return cv
}()
let CelliD = "CelliD"
func handleMoreButton(){
//creating and adding View
if let windowView = UIApplication.shared.keyWindow {
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
let heightCollectionView = CGFloat(300)
let myHeight = height - heightCollectionView
collectionView.frame = CGRect(x: 0, y: height, width: width, height: 0)
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
windowView.addSubview(self.collectionView)
self.collectionView.frame = CGRect(x: 0, y: myHeight, width: width, height: heightCollectionView)
}, completion: nil)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CelliD, for: indexPath)
return cell
}
override init(){
super.init()
collectionView.register(SettingCell.self, forCellWithReuseIdentifier: CelliD)
collectionView.delegate = self
collectionView.delegate = self
}
}
最佳答案
请在您的 init 方法中添加这两行
self.collectionView.delegate = self
self.collectionView.dataSource = yourDataSource
目前你有
collectionView.delegate = self
collectionView.delegate = self
也让你的collectionView变得懒惰......并在那里分配委托(delegate)
private lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = .white
cv.delegate = self
cv.dataSource = yourDataSource
cv.translatesAutoresizingMaskIntoConstraints = false
return cv
}()
关于ios - CollectionViewCells 不会以编程方式出现 - Swift 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61417963/