Andrew Coad
Andrew Coad

Reputation: 335

XCode 8 misplacement of views

I can't figure out what I'm doing wrong here....Super basic stuff but I see no other complaints on the net so maybe it is something I am doing wrong??

I'm using XCode 8 and I find that when aligning a view to the center X of a peer view that is itself centered on the screen, XCode is in fact setting the alignment to the center X of the top-level view. Screen shots: Super basic UIView and UILabel

This is a super basic UIView with a UILabel aligned to the UIView center X (constraint is highlighted). Below is the view hierachy... no surprises...

View hierarchy

And the highlighted constraint:

enter image description here

You can see that the constraint relates the MyLabel.centerX to MyView.centerX as is expected. The relationship is 0.5 which means that MyLabel should be positioned 25% of the way from the left edge of MyView. It is not - if you look carefully at the first screenshot you can see that it is not 25% from the edge of MyView but 25% from the edge of the screen. Changing the Storyboard to an iPad screen as below shows the problem more clearly:

iPad screen

This only seems to happen if the view that you are aligning to is itself centered on the top-level view. As below, if I create another view that is not centered on the top-level view, all is fine.

iPhone SE - non-centered view

And iPad rendition:

iPad view

Any thoughts would be appreciated....

Upvotes: 1

Views: 108

Answers (2)

matt
matt

Reputation: 535138

I think you may just have a misconception about what a multiplier means when applied to a center constraint. A thing is centered in relation to its superview. The easiest way to see this is with a configuration like this:

enter image description here

The orange view knows nothing about centers; it is positioned horizontally by the leading edge constraint that I've highlighted. The blue view has its center x aligned with the orange view's center x, with a multiplier of 2. As you can see, the result has nothing to do with the orange view's width: it means "twice as far to the right as the center of the orange view is".

Upvotes: 0

hooliooo
hooliooo

Reputation: 548

You can see that the constraint relates the MyLabel.centerX to MyView.centerX as is expected. The relationship is 0.5 which means that MyLabel should be positioned 25% of the way from the left edge of MyView.

By putting MyLabel's centerX to MyView's centerX you're not actually aligning MyLabel's centerX to MyView's leading edge...

Since MyView's centerX is aligned to the root UIView's centerX, MyLabel's centerX is doing exactly what you assigned it to do.

Transitive property: if a = b, and b = c then a = c. In this case the centerX of the root UIView (superview)

You should change the second item from MyView.Center X to My View's leading edge

Upvotes: 1

Related Questions