rocket101
rocket101

Reputation: 7537

Centering with Auto layout Xcode

I'm developing a swift app, and I am designing the interface in interface builder in Xcode. My interface (which consists of two UILabels, looks fine in portrait mode, but looks awful in landscape mode.

The issue is that the labels won't stay centered, as I want them, when rotated. I used the following auto layout constraints:

Upper edge constraint: top layout guide 
Lower edge constraint: bottom layout guide
Right edge constraint: standard value
Left edge constraint: standard value

These settings must not be working, as the label doesn't stay centered when rotated. What are the proper constraints to use for auto layout to center this label?

Upvotes: 3

Views: 1116

Answers (1)

ldindu
ldindu

Reputation: 4380

You can achieve the required effect in interface builder, I would advise you to do it using programmatic auto layout constraint.

[self.view addConstraint: [NSLayoutConstraint
    constraintWithItem:self.view 
    attribute:NSLayoutAttributeCenterX 
    relatedBy:NSLayoutRelationEqual 
    toItem:"YOUR VIEW" 
    attribute:NSLayoutAttributeCenterX 
    multiplier:1
    constant:0]];

The above NSLayoutAttributeCenterX attribute centred the "YOUR VIEW" horizontally. For vertical centred layout, you can do so by changing the attribute property to NSLayoutAttributeCenterY for both self.view and "YOUR VIEW".

Upvotes: 2

Related Questions