基于单元格类的CollectionView SizeForItemAt?

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

是否可以包含sizeForItemAt代码以根据单元类动态生成?我有一个collectionView,其中有很多行具有不同类型的单元格,但是没有任何特定的模式(很难为每个单元格键入'if index path.row == 29',依此类推)。

我已经尝试了以下代码的变体,但是它总是返回默认值(否则)。这里的代码段具有3种类型的单元格(GroupCell,MatchingButtonsCell和MatchingEventCell)。

我可以根据单元格类别动态调整尺寸吗?

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if let cell = self.masterCollectionView.cellForItem(at: indexPath) as? GroupCell {
        let cellHeight: CGFloat = (self.view.bounds.height * 0.55)
        let cellWidth: CGFloat = self.masterCollectionView.frame.width
        return CGSize(width: cellWidth, height: cellHeight)
    } else if let cell = self.masterCollectionView.cellForItem(at: indexPath) as? MatchingButtonsCell {
        let cellHeight: CGFloat = 60
        let cellWidth: CGFloat = self.masterCollectionView.frame.width
        return CGSize(width: cellWidth, height: cellHeight)
    } else if let cell = self.masterCollectionView.cellForItem(at: indexPath) as? MatchingEventCell {
        let cellHeight: CGFloat = 500
        let cellWidth: CGFloat = self.masterCollectionView.frame.width
        return CGSize(width: cellWidth, height: cellHeight)
    } else {
        let cellHeight: CGFloat = 10
        let cellWidth: CGFloat = self.masterCollectionView.frame.width
        return CGSize(width: cellWidth, height: cellHeight)
    }

}

谢谢你!

swift xcode uicollectionview uicollectionviewcell uicollectionviewlayout
1个回答
0
投票

我可以根据单元格类别动态调整尺寸吗?

基本上没有。问题是您假设在调用sizeForItemAt时,项目所在的位置是are“单元格”。但这并非一定如此。据您所知,当集合视图仍在计划其布局时,在存在[[any“单元格”之前调用sizeForItemAt

这就是为什么没有在呼叫中给您一个单元的原因。您将得到一个

索引路径

。那应该就是您所需要的。您需要能够基于索引路径,而不是基于“单元格”的内容给出答案。这应该很容易。毕竟,假设您是cellForItemAt实现中的单元格类,并且必须基于索引路径来执行此操作,因为这就是您所拥有的全部信息。好吧,如果您可以根据那里的索引路径进行操作,请根据此处的索引路径进行操作。
© www.soinside.com 2019 - 2024. All rights reserved.