ShurupuS
ShurupuS

Reputation: 2923

add a UIView and recalculate constraints with autolayout

I need your help to make this:

I have a view which width is equal to the width of screen. In this view I have 2 subviews with width 1/2 of parent view and aspect 1:1, so the height of the parent view should be equal to the height of subviews.

enter image description here

After that I need to perform animation which should add to the parent view another view and transform a whole screen like this:

enter image description here

Should I use autolayout programmatically to achieve this? How to get this behaviour easier?

Upvotes: 2

Views: 1819

Answers (2)

Mithun Ravindran
Mithun Ravindran

Reputation: 2312

The easiest way would be.

  • In design time(Storyboard) add 3 views inside the parent view.
  • For all the child views (View 1,2 and 3) create a width constraint and create outlets for the same. When design is completed for all the views, set 0 as constant for the third view's width constraint.
  • Implement "viewDidLayoutSubviews" method for the view controller as below.

    - (void)viewDidLayoutSubviews {
      [super viewDidLayoutSubviews];
    }
    
  • Inside this method, find the current width of the parent view, and store it in a variable "X".

  • When the view is loaded for first time, set the width constraint's constant as x/2 for first and second view.

  • When 3rd view is ready to display, set width constraint's constant as x/3 for all the three view inside an animation block.

Upvotes: 1

Josh Gafni
Josh Gafni

Reputation: 2881

You can...

First, instead of making them half the parent view, I would:

  • Set the left border of the left view to the left border of the parent view.
  • Set the right border of the right view to the right border of the parent view.
  • Set the horizontal space between the left and right views = 0.
  • Set an equal widths constraint between the left and right views.

Then when you add the new view,

  • Remove the right border constraint of the right view.
  • Set the right border of the new view to the right border of the parent view.
  • Set the horizontal space between the right view and new view = 0.
  • Set an equal widths constraint between the right and new views.

Then call

[UIView animateWithDuration:0.5 animations:^{
    [view layoutIfNeeded];
}];

Note that if the default is just two views, you could add the first set of constraints via storyboard (which is easier than doing it programmatically). The rest of it you can do programmatically: See Apple documentation.

Personally, I like this method, because you don't have to do any math on the size or positions of the views - autolayout will figure it out for you.

Upvotes: 2

Related Questions