简体   繁体   English

Swift-集合视图-集合视图中间的中心单元格

[英]Swift - Collection View - Center Cells in the middle of Collection View

I am trying to centre all the cells inside a UICollectionView in its middle. 我试图居中于UICollectionView内部的所有单元格。 The cells are divided as 11x4. 单元格划分为11x4。

I have tried using the code below however, the cells are grouped in one line. 我尝试使用下面的代码,但是,单元格分组在一行中。

What I am trying to achieve is shown in the second image: 我试图实现的目标显示在第二张图片中:

WRONG 错误 在此处输入图片说明

SHOULD BE 应该 在此处输入图片说明

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

    }

Also in my code I amusing collectionViewLayout to divide the cells in 4 lines, maybe I should implement the centering system in here but I cannot get how to achieve this. 同样在我的代码中,我正在使用collectionViewLayout将单元格划分为4行,也许我应该在此处实现居中系统,但是我无法获得实现该目标的方法。 Any Idea?: 任何想法?:

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)
    }

if you prefer a more visual approach try changing the insets 如果您希望使用更直观的方法,请尝试更改插图 如果您希望使用更直观的方法,请尝试更改插图

Found out the Solution: 找到解决方案:

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)
    }

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

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