【问题标题】:UICollectionViewCell not filling the entire screen in Swift 3UICollectionViewCell 没有填满 Swift 3 中的整个屏幕
【发布时间】:2017-04-10 07:29:27
【问题描述】:

我有一个 UICollectionView,它的单元格覆盖了整个屏幕。我的问题是右边有一个小空间显示不同的单元格。我希望每个单元格都覆盖整个屏幕宽度。

这是我尝试过的:

  1. 在 Storyboard 中将最小间距设置为 0
  2. 将每个单元格设置为适合整个视图框架
private func collectionView(collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: view.frame.height)
}

我还应该做些什么来解决这个问题?

【问题讨论】:

    标签: ios swift uicollectionview uicollectionviewcell


    【解决方案1】:

    正确的 Swift 3 实现应该是

        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            let itemWidth = collectionView.bounds.width
            let itemHeight = collectionView.bounds.height
            return CGSize(width: itemWidth, height: itemHeight)
    }
    

    这将使每个集合视图单元格填满整个集合视图。它不应该是私人的。现在您需要做的就是确保您的集合视图延伸到整个视图。

    还要确保扩展您的 ViewController 以包含 UICollectionViewDelegateFlowLayout 以使上述方法正常工作,并将 Storyboard 中的所有部分插入更改为 0。

    【讨论】:

    • 还要确保扩展您的 ViewController 以包含 UICollectionViewDelegateFlowLayout 以使上述方法正常工作,并将 Storyboard 中的所有部分插入更改为 0。 >> 这是我缺少的部分!非常感谢!
    • 拯救了我的一天!谢谢老哥
    【解决方案2】:

    UICollectionViewDelegate、UICollectionViewDataSource、UICollectionViewDelegateFlowLayout

    添加所有 3 名代表很重要。特别是。 UIDelegateFlowLayout。

    【讨论】:

      【解决方案3】:

      只是为了提高投票率最高的答案:您需要添加 UICollectionViewDelegateFlowLayout 一致性,但如果您使用 UICollectionViewController,则不需要这样做 - 它已经符合所有必要的协议。

      进一步,一种更短的实现sizeForItemAt的方法:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-19
        • 1970-01-01
        相关资源
        最近更新 更多