如何在sizeForItem中获取自定义集合视图单元格

时间:2018-03-11 09:49:19

标签: ios swift uikit

如您所知,我们可以使用UICollectionViewDelegateFlowLayout中的sizeForItemAt方法设置UICollectionView单元格大小。 但无法获得具有以下自定义类的单元格。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
  // This will raise runtime errors.
  let cell = collectionView.cellForItem(at: indexPath) as! MyCustomCell
  // Also this.
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "default", for: indexPath) as! MyCustomCell

  return cell.dynamicSize
}

我该怎么办?

2 个答案:

答案 0 :(得分:0)

var size = super.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath)

if let cell = collectionView.cellForItem(at: indexPath) as? MyCustomCell {
    size = cell.dynamicSize
}
return size

答案 1 :(得分:0)

您可以使用 UICollectionViewLayout 执行此操作,如:

override func viewDidLoad() {
    super.viewDidLoad()

    let customLayout = UICollectionViewFlowLayout()
    customLayout.scrollDirection = .horizontal // .vertical
    customLayout.itemSize = CGSize(width: 100, height: 200) // set the item size here .
    customLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    customLayout.minimumLineSpacing = 30
    myCollectoinView.collectionViewLayout = customLayout

    let anotherCustomLayout = UICollectionViewFlowLayout()
    anotherCustomLayout....
    myAnotherCollectoinView.collectionViewLayout = anotherCustomlayout
}

如果你想使用 sizeForItemAt方法

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
      if collectionView == myCollectionView {
         // myCollectionView cell size
         return CGSize(width :100 , height : 100)
      }else { 
         // myAnotherCollectionView cell size
         return CGSize(width: 50 m height : 50)
      }
    }