【发布时间】:2021-08-19 05:40:34
【问题描述】:
我正在制作一个包含 2 个部分的 CollectionView,一切都很好,只是大小。我想在不同的部分给出不同大小的单元格,但是当我调用 sizeForItemAt 时,Xcode 显示黄色警告“将永远不会被执行”。下面是我设置我的 CollectionView 函数的方法:
extension ArtistProfileViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch mySections[section] {
case .profile:
return 1
case .relatedArtists:
return 10
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch mySections[indexPath.section] {
case .profile:
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ArtistProfileCell.identifier, for: indexPath) as? ArtistProfileCell else { return UICollectionViewCell()}
return cell
case .relatedArtists:
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RelatedArtistCell.identifier, for: indexPath) as? RelatedArtistCell else { return UICollectionViewCell()}
cell.myImageView.image = UIImage(systemName: "person")
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
}
这是我设置我的 CollectionView 的方式:
var myCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.estimatedItemSize = .zero
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.register(ArtistProfileCell.self, forCellWithReuseIdentifier: ArtistProfileCell.identifier)
cv.register(RelatedArtistCell.self, forCellWithReuseIdentifier: RelatedArtistCell.identifier)
return cv
}()
我确实在 viewDidLoad 中将 CollectionView.delegate/datasource 设置为 self,我可以看到单元格出现在屏幕上。但是,单元格的大小根本没有变化。另外,我知道解决方案之一是在情节提要中将估计大小设置为无,但我不知道如何以编程方式设置它。所以我不知道它是否有效。
有一点很奇怪,当我调用 sizeForItemAt 时,它并没有自动显示完整的函数。我必须像this一样自己输入。
有人可以帮忙吗?提前致谢!
【问题讨论】:
-
您已将
sizeForItemAt放入另一个函数中。拿出来。
标签: ios swift uicollectionview uicollectionviewcell uicollectionviewflowlayout