Reputation: 8735
I'm trying to center the first and the last cell of a horizontal collection view.
The only approach i found until now was adding extra cells at the begin and the end of my UICollectionView
. This method was totally a bad idea for obvious reasons but I didn't find a better way to do it for now. And since, with the iPhone 6 and the iPhone 6+, the layout of my view is totally broken... (facepalm)
To illustrate my need I need to display something like this :
| x x x x x| where the first x represent my first cell
and
|x x x x x | where the last x represent my last cell
I think using a UICollectionViewFlowLayout
subclass is the proper way to do that with contentInset
stuff but I'm a total newbie with these components.
Any links or suggestions on how to achieve this ?
Upvotes: 4
Views: 3281
Reputation: 190
Easy handle for your different sections.
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(0, collectionView.frame.size.width/2, 0, collectionView.frame.size.width/2);
}
Upvotes: 0
Reputation: 327
Posting here for future reference, as I've been working with same problem, and found a solution. Tested in Xcode Version 8.2.1 (8C1002) with Swift 3
The UICollectionViewDelegate has the func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
To center the first and last cell in the collection view, your calculate the inset by:
let inset: CGFloat = collectionView.frame.width * 0.5 - cellSize.width * 0.5
After this, you simply return the new UIEdgeInsetMake(0, inset, 0, inset)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let inset: CGFloat = collectionView.frame.width * 0.5 - cellSize.width * 0.5
return UIEdgeInsetsMake(0, inset, 0, inset)
}
-------Edit-------
In this case I store the cell size as a hard coded value, and set it by using the delegate func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
Upvotes: 5