Reputation: 8608
iOS newbie here.
I have three UI elements (one UIImageView
and two UILabel
s) that are added to a UIView
(that fills the whole screen)
How do I center them to the middle of the screen, both vertically and horizontally?
Upvotes: 1
Views: 63
Reputation: 4953
Using the verbose AutoLayout syntax, you can set a view's center X and Y coordinates.
[containerView addConstraint:[NSLayoutConstraint constraintWithItem:otherView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:containerView
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0]];
[containerView addConstraint:[NSLayoutConstraint constraintWithItem:otherView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:containerView
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0]];
You can also use an XIB to do this.
Upvotes: 2
Reputation: 6115
In code, without autolayout, you could use autoresizingmasks #oldschool:
imageview.center = view.center;
label.center = view.center;
imageview.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
label.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
Upvotes: 2
Reputation: 17860
By using the Auto-Layout concept. https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/Introduction/Introduction.html
Upvotes: 2