Michael Eilers Smith
Michael Eilers Smith

Reputation: 8608

How to center grouped UI elements in a UIView?

iOS newbie here.

I have three UI elements (one UIImageView and two UILabels) 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

Answers (3)

greg
greg

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

Thomas Keuleers
Thomas Keuleers

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

Related Questions