我从另一个 Collection View 单元格中调用一个新的 Collection View :
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let rezeptLauncher = RezeptLauncher()
rezeptLauncher.ShowRezept()
}
然后它显示 Collection View ,但内部没有单元格。
我几乎阅读了有关该主题的每一页。什么都不起作用。有什么建议么?提前非常感谢您!
class RezeptLauncher: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width / 2.5, height: collectionView.frame.width / 2)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.backgroundColor = .red
return cell
}
var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.backgroundColor = .white
cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
return cv
}()
func ShowRezept() {
print("Rezept wird angezeigt")
if let keyWindow = UIApplication.shared.keyWindow {
keyWindow.addSubview(collectionView)
collectionView.backgroundColor = .white
collectionView.topAnchor.constraint(equalTo: keyWindow.topAnchor, constant: 40).isActive = true
collectionView.leadingAnchor.constraint(equalTo: keyWindow.leadingAnchor, constant: 40).isActive = true
collectionView.trailingAnchor.constraint(equalTo: keyWindow.trailingAnchor, constant: -40).isActive = true
collectionView.bottomAnchor.constraint(equalTo: keyWindow.bottomAnchor, constant: -40).isActive = true
collectionView.delegate = self
collectionView.dataSource = self
collectionView.reloadData()
}
}
}
最佳答案
您的 Rezept 对象似乎正在被 Swift 释放,因为它的生命周期位于您的 did select 函数内。
如果它被释放,collectionView就不再有委托(delegate)了。由于按照最佳实践,代表是弱实体,因此他们不会被牢固地持有(因此解除分配将其删除)
您应该将其添加为保存外部 CollectionView 的类的实例,并且仅调用 didSelect 内部的 setup 函数。
关于swift - UICollectionView - 为什么不调用这些方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57737936/