I have a UICollection view that is inside another UIView. I am trying to center the collection view inside its parent view. Currently manually doing it by tweaking its frame (see code below). There has to be a easier way.
CURRENT CODE:
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(COLLECTION_PADDING+10, COLLECTION_PADDING+5, self.bounds.size.width - (COLLECTION_PADDING*2), self.bounds.size.height - (COLLECTION_PADDING+22)) collectionViewLayout:flow];
You can setup your collectionView's width and height and then use the
center
property to adjust it's location.EDIT: As Logan just mentioned in the comments, this only works if self and self.collectionView have the same superview. If you are adding collectionView to a view and want it centered inside that view then you could do:
But this case doesn't work when there is rotation involved. In that case you would have to use other means. So, as anything in coding, this is not a clear cut answer. But for most cases it will work. If you are getting into the rare cases that it does not work then you are likely going to do more custom framing than just centering inside parents.
Heard of Layouts?..This might help you.
This is for horizontal alignment
This is for vertical alignment
You could do something like this:
Swift 3:
With this approach, your subview will be centered in its superview regardless of the superview's coordinates. Using an approach like this:
Will cause problems if the superview has an origin of anything other than 0,0
IMO, you could try finding the difference between your collectionview and your parent view size. Then dividing by 2 and padding all sides with that.