iOS - UIView setCenter在UIView animateWithDuration中不起作用

时间:2016-01-08 10:55:22

标签: ios objective-c iphone animation uiview

我的问题让我发疯,我想我还没有足够的知识来找到这个问题的答案。

这里有一个完美运作的代码:

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);

给我以下输出:

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

现在,如果我将此setCenter放入UIView animationWithDuration中,就像这样

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);
}];

我得到了这个输出:

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

你们有什么想法吗? 我检查了约束和autoLayout,一切都很好。

2 个答案:

答案 0 :(得分:6)

试试这个:

<强>目标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)

答案 1 :(得分:0)

如果您使用自动布局,只有更改中心或框架无效,自动布局系统会自动更正。您需要更改约束,或者不要对视图使用约束。

自动布局将在layoutSubviews时激活,这通常在下一个运行循环中调用。这就是为什么你第一次没有动画代码工作。但动画中的一个回调在完整的块中,有一个延迟和中心已经得到纠正。