简体   繁体   中英

iOS - UIView setCenter not working when in an UIView animateWithDuration

I've a problem that is driving me crazy, and I guess I've not enough knowledge to find an answer to this problem.

here a code that is working perfectly :

NSLog(@"%f, %f", imageList.center.x, imageList.center.y);
[imageList setCenter:CGPointMake(imageList.center.x, -imageList.center.y)];
NSLog(@"=> %f, %f", imageList.center.x, imageList.center.y);

giving me the following output :

2016-01-08 11:48:42.585 User[4047:600095] 160.000000, 284.000000
2016-01-08 11:48:42.585 User[4047:600095] => 160.000000, -284.000000

Now, if I put this setCenter into an UIView animationWithDuration, like this

NSLog(@"%f, %f", imageList.center.x, imageList.center.y);
[UIView animateWithDuration:0.3 animations:^{
   [imageList setCenter:CGPointMake(imageList.center.x, -imageList.center.y)];  
} completion:^(BOOL finished) {*/
    NSLog(@"=> %f, %f", imageList.center.x, imageList.center.y);
}];

I'm getting this output :

2016-01-08 11:48:42.585 User[4047:600095] 160.000000, 284.000000
2016-01-08 11:48:42.585 User[4047:600095] => 160.000000, 284.000000

Do you guys have any idea why ? I checked the constraints and the autoLayout, everything is fine there.

Try this :

Objective-C

[UIView animateWithDuration:0.3 delay:0.0 options:(UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction) animations:^{
    [imageList setCenter:CGPointMake(imageList.center.x, -imageList.center.y)];
} completion:nil];

Swift 4

UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveLinear, animations: {
    imageList.center = CGPoint(x: imageList.center.x, y: -imageList.center.y)
}, completion: nil)

If you use autolayout, only change center or frame will have no effect, auto layout system will correct it automatically . you need to change your constraints, or not use constraint for your view.

Auto layout will activate when layoutSubviews, this normally called at next run loop. that's why you first no animated code work. But the animation one callback in the complete block, which have a delay and center already got corrected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM