iOS: How to Align The Center of a View With The Bottom of Another View With AutoLayout

前端 未结 6 660
离开以前
离开以前 2021-02-02 15:52

I want to make the center of the head imageView with the bottom of the blue title imageView\'s keep alignment.

How can I do it by using Autolayout?

screen 4.0inc

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-02 16:25

    There are a lot of ways to do this. I'll just show one of the ways.

    OK, Let's do this step by step.

    Step 1

    First, in order to align the center of the oval image with the bottom of the rectangular image, we need to embed the rectangular view in another view in which we could name as the Container View.

    This container view will have the ff attributes:

    • transparent background color
    • width is equal to the screen width
    • height will be twice the height of the rectangular view(Later you
      will know why).

    For the constraints of the Container View:

    • Leading is equal to super view's leading
    • top space to super view is 0
    • Centered horizontally in super view.
    • set aspect ratio with self.

    Once you are done, the constraints will look like this.

    Step 2

    Now for the rectangular image view, the constraints would be:

    • Leading is equal to the container view's leading
    • Top space to container view is 0
    • Trailing is equal to container view's trailing.
    • Set aspect ratio with oval image view

      • By setting aspect ratio with the oval image view. The change in size of this rectangular view will be proportional with the change of size of the oval view.

    It will look like this:

    Step 3

    This time, the contraints of the oval view:

    • centered horizontally in container view
    • centered vertically also in container view
    • set aspect ratio with self

      • Setting aspect ration with self ensures that when the rectangular view expands in size, the change in size of the oval view will not cause distortion.

    This will be the result:

    Step 4

    There one very important view to add. This view will ensure that the rectangular view will always be half the size of the container view so that the center of the oval view will always be aligned with the bottom of the rectangular view. So, we call this view that we will be adding, the dummy view.

    The dummy view will have the ff attributes:

    • transparent background color
    • width and height value should only be 1

    The dummy view's contraints:

    • centered vertically in the container view
    • centered horizontally in the container view
    • width and height are fixed.
    • assign vertical spacing with rectangular view

    This is how it should be done:

    Alright, if you did the steps above you will achieve the effect.

    This will be the overview of the constraints:

    I hope this helps. :)

    Proof that this works!

    I ran it in the simulator... :D

    iPhone 4:

    iPhone 5:

    iPhone 6:

    iPhone 6 Plus:

提交回复
热议问题