Why is this view centered horizontally when its aligned to a vertical axis

707 views Asked by At

Okay so I am new to the Swift programmming language and IOS platform however I have a strong background in mobile development on other platforms such as Android/WP/Xamarin so I decided to just dive in and learn the layout system starting with Auto Layout.

Here I am trying to center a view horizontally and align it to the bottom of the screen using the Auto Layout API via PureLayout. When I set the view to align to the horizontal axis of it's superview this is result I get.

Code

override func updateViewConstraints() {
    if(!didSetupConstraints)
    {

        blackView.autoPinToBottomLayoutGuideOfViewController(self, withInset: 10)
        blackView.autoSetDimensionsToSize(CGSize(width:50,height: 50))
        blackView.autoAlignAxisToSuperviewAxis(.Horizontal)


        didSetupConstraints=true
    }

    super.updateViewConstraints()
   }

Result

enter image description here

However when I set the view to align to the vertical axis I get the desired end result

Code

override func updateViewConstraints() {
    if(!didSetupConstraints)
    {

        blackView.autoPinToBottomLayoutGuideOfViewController(self, withInset: 10)
        blackView.autoSetDimensionsToSize(CGSize(width:50,height: 50))
        blackView.autoAlignAxisToSuperviewAxis(.Vertical)


        didSetupConstraints=true
    }

    super.updateViewConstraints()
   }

Result

enter image description here

Even though I got the result that I wanted, I did not feel good about proceeding without properly understanding why it got aligned in the center horizontally by setting the view to align to it's superview's vertical axis. So can someone explain to me the whole notion of aligning to axes and how they work in Auto Layout. Thanks in advance.

1

There are 1 answers

1
Craig Siemens On BEST ANSWER

Being centered horizontally and aligning to the vertical axis are the same thing.

The vertical axis is a imaginary vertical line that is centered between the views left and right edge. So if a view is aligned with it, the view will be positioned anywhere along that vertical line, causing the view to be entered horizontally.

The source for Pure Layout also has a definition and shows how they map to regular auto layout if that helps.

/** A vertical line equidistant from the view's left and right edges. */
ALAxisVertical = NSLayoutAttributeCenterX,
/** A horizontal line equidistant from the view's top and bottom edges. */
ALAxisHorizontal = NSLayoutAttributeCenterY,