同一个XIB中不同UICollectionView的不同插入

时间:2015-05-29 09:45:29

标签: ios swift uicollectionview uicollectionviewcell

我的视图中有多个UICollectionView控件。每个项目都有不同数量的项目,有些项目足以填满屏幕的宽度,但有些项目只有少数项目无法填满屏幕宽度。对于第二组UICollectionView,我想对内容进行水平居中:

enter image description here

此功能设置UICollectionView

的布局
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    var cellWidth : CGFloat = 110

    var numberOfCells = floor(self.view.frame.size.width / cellWidth)
    var edgeInsets = (self.view.frame.size.width - (numberOfCells * cellWidth)) / (numberOfCells + 1)

    return UIEdgeInsetsMake(0, edgeInsets, 0, edgeInsets)
}

我的问题是如何获得每个UICollectionView单元格宽度

2 个答案:

答案 0 :(得分:0)

当项目数较少时,将项目置于collectionView中心。使用以下代码

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
var insets : UIEdgeInsets = UIEdgeInsetsZero;

var collectionViewFlowLayout : UICollectionViewFlowLayout = collectionViewLayout as UICollectionViewFlowLayout
var itemWidth = collectionViewFlowLayout.itemSize.width
var itemSpacing = collectionViewFlowLayout.minimumInteritemSpacing

// Change this to the number of items in section
var numOfItem : CGFloat = 2
var totalWidth = (numOfItem * itemWidth) + (numOfItem - 1 ) * itemSpacing;

if (totalWidth < collectionView.frame.size.width)
{
    insets.left = (collectionView.frame.size.width - totalWidth) * 0.5 - itemSpacing;
}

return insets;

}

答案 1 :(得分:0)

由于只有单元格的数量是可变的,所以这个技巧有效:

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

    var cellWidth : CGFloat = 110;

    var numberOfCells = floor(screenSize.width / cellWidth)
    var edgeInsets = (self.view.frame.size.width - (numberOfCells * cellWidth)) / (numberOfCells + 1)

    if(collectionView == alignmentsCV){
        //alignmentCV cell size is 50x50
        cellWidth = 50

        var numberOfItems = collectionView.numberOfItemsInSection(0)
        println(numberOfItems)
        println(screenSize.width)
        var wholeItemsWidth = CGFloat(numberOfItems) * cellWidth
        println(wholeItemsWidth)
        if wholeItemsWidth < screenSize.width {
            var freeSpace : CGFloat = (screenSize.width - wholeItemsWidth) / 2

            return UIEdgeInsetsMake(0, freeSpace , 0, freeSpace)

        }else{
            return UIEdgeInsetsMake(0, edgeInsets, 0, edgeInsets)
        }

    }else{
        return UIEdgeInsetsMake(0, edgeInsets, 0, edgeInsets)
    }

}

输出:

enter image description here