How to add an animation to a uiview using autolayout

Source: Internet
Author: User

When we use autolayout to automatically layout A uiview, it means that we give up the traditional

Manually modify and determine the position and size attributes of a view by setting its frame. Even from some

To a certain extent, we should forget the frame attribute of the View: its confirmation no longer depends on me (manual direct modification ),

Instead, we use the constraints provided in the storyboard or code

Bureau engine (Apple uses the cassowary Layout Engine for autolayout. For more information, see: Click to open the link .)

Calculate the frame of the view. Therefore, we can consider that the frame attribute of the view using autolayout is a read-only

. The frame of the view modified in the Code does not produce a real effect on the frame of the view (

This is true ).

Now the problem arises. In the past, we often used modifications to a view frame to produce the animation effect of the view movement.

If so, how can we achieve the same effect in the View world using autolayout? The answer is:

By changing a constraint on this view and triggering it in the animation block of the uiview

Layout.

I. Expected results

The following is a simple example:

As shown in, the entire interface uses autolayout. Now we want to achieve this effect: When

When we click the "display birthday" button, the entire view slides up and a date selector is pushed up.

(Date Picker), similar to clicking textfield. After the keyboard is displayed, the entire interface is moved up to avoid being masked.

Animation effect. After selecting the completion date, click the "birthday date" button or the "finish" button to scale down the entire view.

The Date Picker slides down the visible range.

II. Implementation Details

First, let's take a look at the hierarchical structure of the view in the storyboard: As shown in, we can see that,

The layout of the entire view is quite simple. There are two levels: Root View and our Date Picker view, where date

The picker view contains a completion button and a system Date Picker. In this way, the entire view and

The Date Picker view is moved up at the same time. We only need to animation the Root View and Date Picker view at the same time.

You can.


Consider how to achieve the animation effect of the Root View. Here we can skillfully modify the bounds attribute of the Root View.

To achieve the Root View's up effect. Note that we need to understand the difference between the bounds attribute of the view and the frame attribute,

The former is relative to the local coordinate system of the current view, while the latter is relative to the coordinates of the parent view of the current view.

System.
In short, frame determines the position and size information of a view relative to the parent view. While bounds decides

Specifies the position of the content displayed by the current view relative to the local coordinate system. Here we will show the visual content and

Subviews can be viewed as content information on a page, while views can be viewed as a magnifier placed on paper,

The size of a magnifier is not necessarily the same as that of a paper. The role of the bounds attribute is to determine this

The location of the magnifier relative to the paper: A bounds = (0,200,300,300) means that we want to direct this magnifier

The bottom of the paper moves 200 points, but the position of the magnifier remains unchanged relative to the parent view.

As a result, the view (displayed content) is moved up to 200 points.


Modifying the origin attribute of bounds does not change the frame of the view.

We have an illusion that the view is moving up. For example, "which position..." is shown in a magnifier.

The first line.
The result of moving the painting on the Root View is solved. Next let's look at the Date Picker

Storyboard has the following constraints: fixed height of 207, trailing/leading/top relative to super

The location of the view (Root View.


The constraint for determining whether the Date Picker view is to move up or down in the Y axis is obviously the top constraint. Click the top constraint,

You can see the details of this constraint:

A constraint can be described as: firstitem. attributea = seconditem. attributeb * Multipler +

Constant.

In combination, we can conclude that the top constraint of Date Picker view is

Datepickerview. Top = toplayoutguide. Bottom X 1 + 400

We can modify the top constraint by modifying the constant value here to achieve the expected effect.

Modify instead of deleting the old constraint and add a new constraint, which is also recommended by Apple.

The nslayoutconstraint. h header file is described as follows:


In this way, the top constraint of the Date Picker view can be obtained and modified to move it up and down. Note:

The top constraint for obtaining datepicker view in the Code is actually to be searched in the constraints array of its parent view,

This is because the constraints array of each view stores a set of constraints required by the layout subview.

We also need to define an auxiliary bool variable. We have determined whether the Date Picker view is popped up:

<span style="font-size:18px;">@property (nonatomic, assign) BOOL hasShowPickerView;</span>

Next, define an auxiliary function to find the top constraint of the Date Picker view and modify its constant attribute

Given value:

- (void)replacePickerContainerViewTopConstraintWithConstant:(CGFloat)constant{    for (NSLayoutConstraint *constraint in self.pickerContainerView.superview.constraints) {        if (constraint.firstItem == self.pickerContainerView && constraint.firstAttribute == NSLayoutAttributeTop) {            constraint.constant = constant;        }    }}


In the code, the superview of the picker container view (that is, the Date Picker view in the text)

If you find that the firstitem and firstattribute attributes are Date Picker view and

Top, the constraint is the target constraint, and then its constant attribute is modified.
When the view is loaded for the first time, we want to ensure that the Date Picker view is at the bottom of the entire view, that is, the hidden state.

Therefore, we call the auxiliary method in viewdidload method of viewcontroller to modify the Date Picker.

Top constraint of view:

<span style="font-size:18px;">[self replacePickerContainerViewTopConstraintWithConstant:self.view.frame.size.height];</span>

When you click the birthday button for the first time, the animation changes the top of the bounds and Date Picker views of the Root View.

Constraint. Pay attention to the calculation of the upstream gap. Click the birthday button again to restore the bounds of the Root View.

To the normal value, the top constraint of Date Picker view is also restored to the value set in viewdidload:

</pre><p class="p1"></p><pre name="code" class="objc"><span style="font-size:18px;">- (IBAction)didTapOnBirthdayButton:(id)sender{    self.hasShowPickerView = !self.hasShowPickerView;    if (self.hasShowPickerView) {        CGRect birthdayButtonFrame = self.birthdayButton.frame;        birthdayButtonFrame = [self.view convertRect:birthdayButtonFrame fromView:self.birthdayButton.superview];        CGFloat birthdayButtonYOffset = birthdayButtonFrame.origin.y + birthdayButtonFrame.size.height;        CGFloat gap = birthdayButtonYOffset - (self.view.frame.size.height - self.pickerContainerView.frame.size.height);        CGRect bounds = self.view.bounds;        if (gap > 0) {            bounds.origin.y = gap;        } else {            gap = 0;        }        [self replacePickerContainerViewTopConstraintWithConstant:birthdayButtonYOffset];        [UIView animateWithDuration:0.25 animations:^{            self.view.bounds = bounds;            [self.view layoutIfNeeded];        }];    } else {        [self replacePickerContainerViewTopConstraintWithConstant:self.view.frame.size.height];        CGRect bounds = self.view.bounds;        bounds.origin.y = 0;        [UIView animateWithDuration:0.25 animations:^{            self.view.bounds = bounds;            [self.view layoutIfNeeded];        }];    }}</span>


It is okay to remove [self. View layoutifneed] from the above Code. The root view may be confusing.

The key to the calculation of bounds. Origin. Y's upstream gap and the calculation of the top constraint's constant value is true.

The meaning of the frame and bounds of the view.

So far, the program has achieved the expected results.

Iii. Summary

Before using autolayout, we wrote a program control interface, which is like opening a manual car.

Frequent shift (frame modification) is cumbersome, but it also enjoys the freedom that can completely control the car's gear. Used

After autolayout, the vehicle is upgraded to an automatic shift. We can only switch the shift position instead of directly operating it.

The size of the gas pedal (constraints) is used to indirectly change the vehicle's gear. In an automatic car, we must release

It is impossible to discard the idea of directly controlling the gear position. We must learn to master the accelerator and brakes at our feet.

To control the speed! After getting used to automatic transmission, I believe that everyone can do what they want.


How to add an animation to a uiview using autolayout

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.