簡體   English   中英

Swift-集合視圖-集合視圖中間的中心單元格

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

我試圖居中於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)
    }

如果您希望使用更直觀的方法,請嘗試更改插圖 如果您希望使用更直觀的方法,請嘗試更改插圖

找到解決方案:

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