Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

ios - Animating/Moving views under usage of Autolayout

I want to move a view from one postion to another, I can implement it using

self.view.center = CGPointMake(100, 200);

however, if the project is using Autolayout, then the view will be back to original position after running:

[self.view.superview setNeedsLayout];

then how to actually move a view to new position?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With AutoLayout enabled, we should FORGET FRAMES and only CONSIDER CONSTRAINTS.Yes, for animating also you can no longer change the frame or center, view's will revert back to their original position when layout is called.

Instead you should consider changing the constant value of the constraint to get the same effect.

Consider a User Interface like the image given below.I have a image view with a 20 points leading space from it's superview that means it has a horizontal space constraint with it's superview.Also I have three more constraints attached to that image view, top, width and height.

I will show you how we can animate the image from left to right as shown in the image.

Create IBOutlet's for the constraint's we need to animate.Here we are taking only horizontal space constraint, that is enough to move this view from the left to right.

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *horizontalSpaceConstraint;

enter image description here

Inside Go Away action, we need to update the constant value of this constraint.

- (IBAction)moveFrontAction:(id)sender {
    self.horizontalSpaceConstraint.constant = 220;

    [UIView animateWithDuration:0.5 animations:^{
         [self.imageView layoutIfNeeded];
    }];
}

Now the view should be moved to the right end.I'm just doing that inside a animation block so we will be able to see a nice animation from left to right and vice versa.In Production, we should not hard code the values like this.Just doing it here to make the concept clear.

enter image description here

Inside the Come Back action, we are again resetting the constant back to it's original value, so you can see the orange image animating back to the original location.

- (IBAction)moveBackAction:(id)sender {
    self.horizontalSpaceConstraint.constant = 20;

    [UIView animateWithDuration:0.5 animations:^{
        [self.imageView layoutIfNeeded];
    }];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...