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

时间:2016-08-05 16:29:00

标签: ios swift2 uicollectionview uicollectionviewlayout

我试图将所有细胞集中在UICollectionView的中间。细胞分为11×4。

我尝试过使用下面的代码,然后将单元格分成一行。

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

WRONG enter image description here

应该是 enter image description here

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

找到解决方案:

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