0

我想UICollectionView的項是在中央,所以我寫了下面的代碼:設置UICollectionView的UIEdgeInsets

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { 
    let collectionViewWidth = collectionView.bounds.width 
    let collectionViewHeight = collectionView.bounds.height 
    let numberOfRows = CGFloat(collectionView.numberOfItemsInSection(0)) 
    let leftValue = (collectionViewWidth/2.0) - (numberOfRows * 5) - (numberOfRows * (collectionViewHeight/2.0)) 
    print(leftValue) 
    return UIEdgeInsets(top: 0, left: leftValue, bottom: 0, right: 0) 
} 

但現在的問題是,我不能滾動,以左側爲我的左插圖變化,請建議我任何解決方案。

回答

0

我想通了這一點做一些計算和所有的,所以這裏是代碼:

func refreshCollectionView(count: Int) { 
    let collectionViewHeight = collectionView.bounds.height 
    let collectionViewWidth = collectionView.bounds.width 
    let numberOfItemsThatCanInCollectionView = Int(collectionViewWidth/collectionViewHeight) 
    if numberOfItemsThatCanInCollectionView > count { 
     let totalCellWidth = collectionViewHeight * CGFloat(count) 
     let totalSpacingWidth: CGFloat = CGFloat(count) * (CGFloat(count) - 1) 
     // leftInset, rightInset are the global variables which I am passing to the below function 
     leftInset = (collectionViewWidth - CGFloat(totalCellWidth + totalSpacingWidth))/2; 
     rightInset = -leftInset 
    } else { 
     leftInset = 0.0 
     rightInset = -collectionViewHeight 
    } 
    collectionView.reloadData() 
} 

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { 
    return UIEdgeInsetsMake(0, leftInset, 0, rightInset) 
} 

如需更詳細的代碼,你可以在這裏看到我的代碼https://github.com/anirudha-music/CollectionViewCenter

相關問題