Center the UIView vertically and horizontally within the parent view

I have a UICollection view that is inside another UIView. I am trying to center the collection view inside my parent view. Currently, this is done manually by adjusting its frame (see code below). There should be an 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];
+4
source share
4 answers

You can do something like this:

self.collectionView.center = CGPointMake(CGRectGetMidX(superview.bounds), CGRectGetMidY(superview.bounds));

Swift 3:

self.collectionView.center = CGPoint(superview.bounds.midX, superview.bounds.midY)

With this approach, your unit will be concentrated in its supervisor, regardless of the coordinates of the supervisor. Using this approach:

self.collectionView.center = superview.center

, , 0,0

+18

, center .

self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,width,height)];
self.collectionView.center = CGPointMake(self.center.x,self.center.y);

EDIT: , , self self.collectionView . collectionView , , :

self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,width,height)];
self.collectionView.center = CGPointMake(self.center.x - self.frame.origin.x/2,self.center.y - self.frame.origin.x/2);

, . . , - , . . , , , , , .

+3

?.. .

NSLayoutConstraint *centerHcons =[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:collectionViewSuper attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f];

NSLayoutConstraint *centerVcons =[NSLayoutConstraint constraintWithItem:self.collectionView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:collectionViewSuper attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f];

    [collectionViewSuper addConstraints:@[centerHcons, centerVcons]];
+2

IMO, . 2 .

parentHeight = self.bounds.size.height;
parentWidth = self.bounds.size.width;
heightDiff = parentHeight - collectionview.bounds.size.height;
widthDiff = parentWidth - collectionview.bounds.size.width;
heightPadding = heightDiff/2;
widthPadding = widthDiff/2;

self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(widthPadding, heightPadding, parentWidth-widthPadding, parentHeight-heightPadding) collectionViewLayout:flow];
+1

All Articles