2015-05-29 17 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

相關問題