CollectionViewCells不会以编程方式显示-Swift 5

问题描述 投票:1回答:1

我想显示一个在按下按钮后随动画一起显示的collectionView。

collectionView正确显示,但其中的collectionViewCells不正确。

我已经正确设置了UICollectionViewDelegate和UICollectionViewDataSource方法,但未调用它们(已通过breakPoints测试)。

我正在做所有的事情([以编程方式,所以我还必须将[UI]通用UICollectionViewCell的SettingCell注册到相应的cellID。

[我还认为可能会出现问题,因为我设置委托和数据源的时间太晚了,但我不这么认为,因为它们是在父类的开始时设置的。

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 } }

ios swift uicollectionview uicollectionviewcell
1个回答
2
投票
请在您的init方法中添加这两行

self.collectionView.delegate = self self.collectionView.dataSource = yourDataSource

当前您正在拥有

collectionView.delegate = self collectionView.delegate = self

还使您的collectionView变得懒惰...并在其中分配委托

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 }()

© www.soinside.com 2019 - 2024. All rights reserved.