繁体   English   中英

具有固定列数和动态单元格高度的 UICollectionView

[英]UICollectionView with fixed number of columns and dynamic cell height

可以找到很多关于 UICollectionView 的好信息,但我无法回答这个问题:

当单元格具有动态高度时,您将如何创建具有固定列数的垂直滚动 UICollectionView。

我的计划是使用自动调整大小的单元格,但由于我想要固定数量的列,这将要求每个单元格具有从 collectionview 宽度计算的宽度约束,这似乎很古怪,并且在更改设备方向时可能会出现问题。 具体来说,我希望该集合在紧凑的单列上和常规的两列上。

我也试图实现collectionView(UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSizeUICollectionViewDelegateFlowLayout这种方式可以很容易地设置单元格的宽度,以便它适合我想要的列数,但现在看来,这是不可能的结合这与自我调整单元格高度。

使用以下枚举创建一个助手类。

enum DeviceTraitStatus {
    ///IPAD and others: Width: Regular, Height: Regular
    case wRhR
    ///Any IPHONE Portrait Width: Compact, Height: Regular
    case wChR
    ///IPHONE Plus/Max Landscape Width: Regular, Height: Compact
    case wRhC
    ///IPHONE landscape Width: Compact, Height: Compact
    case wChC

    static var current:DeviceTraitStatus{

        switch (UIScreen.main.traitCollection.horizontalSizeClass, UIScreen.main.traitCollection.verticalSizeClass){

        case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.regular):      
            return .wRhR
        case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.regular):
            return .wChR
        case (UIUserInterfaceSizeClass.regular, UIUserInterfaceSizeClass.compact):
            return .wRhC
        case (UIUserInterfaceSizeClass.compact, UIUserInterfaceSizeClass.compact):
            return .wChC
        default:
            return .wChR

        }

    }

}

然后在集合视图委托方法中相应地计算宽度。

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

private func size(for indexPath: IndexPath) -> CGSize
{
    let cell = Bundle.main.loadNibNamed("YourCollectionViewCell", owner: self, options: nil)?.first as! BoxSelectCollectionCell

    cell.setNeedsLayout()
    cell.layoutIfNeeded()

    // Call the method to calculate the width
    var width: CGFloat = 0
    switch DeviceTraitStatus.current
   {
          case .wChR, .wChC: width = (collectionView.frame.size.width - padding/2).rounded(.down)

          case .wRhR, .wRhC: width = (collectionView.frame.size.width/2 - padding/2).rounded(.down)

   }
    let height: CGFloat = 0

    let targetSize = CGSize(width: width, height: height)

    var size = cell.contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: .defaultHigh, verticalFittingPriority: .fittingSizeLevel)

    return size
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM