【问题标题】:UICollectionViewCell Size According to Screen/ FrameSize SwiftUICollectionViewCell 大小根据 Screen/FrameSize Swift
【发布时间】:2015-09-14 17:43:06
【问题描述】:

我有一个集合视图,每个集合视图单元中都有一个图像。对于任何给定的帧/屏幕尺寸,我只想有 3 个单元格。我该如何实现这一点。我写了一些基于this post的代码

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let numberOfCell = 3
    let cellWidth: CGFloat = [[UIScreen mainScreen].bounds].size.width/numberOfCell
    return CGSizeMake(cellWidth, cellWidth)
    }

但它不起作用并给出错误。最好的方法是什么。

【问题讨论】:

    标签: ios swift uicollectionviewcell


    【解决方案1】:

    这是您的快速代码:

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    
        let numberOfCell: CGFloat = 3   //you need to give a type as CGFloat
        let cellWidth = UIScreen.mainScreen().bounds.size.width / numberOfCell
        return CGSizeMake(cellWidth, cellWidth)
    }
    

    这里numberOfCell的类型必须是CGFloat,因为UIScreen.mainScreen().bounds.size.width返回一个CGFloat值所以如果你想用numberOfCell除然后输入numberOfCell必须是CGFloat因为你可以不要将CGFloatInt 分开。

    【讨论】:

    • ...如果我这样做,单元格之间会有间隙...这是我不想要的,我希望在所有屏幕和所有方向上水平和垂直都有 5 px 的间隙。细胞数量按此顺序增加和减少。您能帮忙吗?
    • 在添加委托类时不要忘记添加“UICollectionViewDelegateFlowLayout” - @JayprakashDubey
    【解决方案2】:

    这是 Swift 3 代码,你必须实现 UICollectionViewDelegateFlowLayout

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let numberOfCell: CGFloat = 3   //you need to give a type as CGFloat
        let cellWidth = UIScreen.main.bounds.size.width / numberOfCell
        return CGSize(width: cellWidth, height: cellWidth)
    }
    

    【讨论】:

    • 添加委托类时不要忘记添加“UICollectionViewDelegateFlowLayout”
    【解决方案3】:

    试试这个, 根据屏幕大小和方向指定 collectionView 单元格项目的大小。 你可以看看this

    希望这会有所帮助。

    【讨论】:

      【解决方案4】:

      Swift3、Xcode 8 的答案,水平间距固定:

      所有早期答案的问题是单元格大小是给定的行和不需要的额外间距。

      func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
          let linespacing = 5          //spacing you want horizantally and vertically
          let numberOfCell: CGFloat = 3   //you need to give a type as CGFloat
          let cellWidth = UIScreen.mainScreen().bounds.size.width / numberOfCell
          return CGSizeMake(cellWidth - linespacing, cellWidth - linespacing)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-04
        • 1970-01-01
        • 1970-01-01
        • 2019-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多