2015-05-29 71 views
0

我在我的视图中有多个UICollectionView控件。每个人都有不同数量的项目,有些人有足够的空间来填充屏幕的宽度,但其中一些只有少数不能满足屏幕宽度的项目。因为我想在第二组的UICollectionView小号水平居中内容:不同的插入不同的UICollectionView在同一个XIB

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的宽度

+0

你想保持ItemWidth常数和水平居中内容? –

回答

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; 

} 
+0

我希望你注意到我正在使用Swift – Maysam

+0

@AshishKakkad对不起,';'固定 – Maysam

+0

@AshishKakkad我不能让你的代码工作,顺便说一句 – Maysam

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

相关问题