[英]How to get a custom collection view cell in sizeForItem
如您所知,我們可以使用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
}
我該怎么辦?
var size = super.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath)
if let cell = collectionView.cellForItem(at: indexPath) as? MyCustomCell {
size = cell.dynamicSize
}
return size
您可以使用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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.