【问题标题】:Swift - Collection View - Center Cells in the middle of Collection ViewSwift - Uicollectionview - 集合视图中间的中心单元格
【发布时间】:2016-08-05 16:28:59
【问题描述】:

我试图将所有单元格集中在中间的 UICollectionView 中。单元格被划分为 11x4。

我尝试过使用下面的代码,但是单元格被分组在一行中。

第二张图片显示了我想要实现的目标:

错了

应该是

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let letterCell = collectionView.dequeueReusableCellWithReuseIdentifier("letterCell", forIndexPath: indexPath) as! LetterCellView

        letterCell.center.y = self.view.center.y

        return letterCell

    }

另外在我的代码中,我很有趣 collectionViewLayout 将单元格分成 4 行,也许我应该在这里实现居中系统,但我不知道如何实现这一点。有什么想法吗?:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

        let totalCellWidth = 30 * 11
        let totalSpacingWidth = 2 * (11 - 1)

        let leftInset = (self.view.frame.size.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
        let rightInset = leftInset

        return UIEdgeInsetsMake(0, leftInset, 0, rightInset)
    }

【问题讨论】:

    标签: ios swift2 uicollectionview uicollectionviewlayout


    【解决方案1】:

    如果您喜欢更直观的方法,请尝试更改插图

    【讨论】:

      【解决方案2】:

      找到解决方案:

      func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
      
              let totalCellWidth = 30 * 11
              let totalSpacingWidth = 2 * (11 - 1)
      
              let leftInset = (self.view.frame.size.width - CGFloat(totalCellWidth + totalSpacingWidth)) / 2;
              let rightInset = leftInset
      
              let totalCellHeight = 30 * 4
              let totalSpacingHeight = 5 * (4 - 1)
      
              let topInset = (self.view.frame.size.height - CGFloat(totalCellHeight + totalSpacingHeight)) / 2;
              let bottInset = topInset
      
              return UIEdgeInsetsMake(topInset, leftInset, bottInset, rightInset)
          }
      

      【讨论】: