Reputation: 3470
I am trying to centre all the cells inside a UICollectionView
in its middle. The cells are divided as 11x4.
I have tried using the code below however, the cells are grouped in one line.
What I am trying to achieve is shown in the second image:
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
}
Also in my code I amusing collectionViewLayout
to divide the cells in 4 lines, maybe I should implement the centering system in here but I cannot get how to achieve this. Any Idea?:
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)
}
Upvotes: 1
Views: 2110
Reputation: 3470
Found out the Solution:
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)
}
Upvotes: 1