【问题标题】:Difference between [UIView beginAnimations:context:] and [UIView animateWithDuration:animations:][UIView beginAnimations:context:] 和 [UIView animateWithDuration:animations:] 的区别
【发布时间】:2010-10-09 18:17:23
【问题描述】:

在我看来这两个类方法是不可互换的。我有一个 UIView 的子视图,在 touchesBegan 方法中有以下代码:

if (!highlightView) {
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Highlight"]];
    self.highlightView = tempImageView;
    [tempImageView release];

    [self addSubview:highlightView];
}

highlightView.alpha = 0.0;

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
highlightView.alpha = 1.0;
[UIView commitAnimations];

当我触摸 Button 时,高亮会淡入,正如您所期望的那样。当我立即触摸时(在动画完成之前),我的 touchesEnded 被调用。这是我想要的行为。

但是现在,我已经成为积木的忠实粉丝,并尝试尽可能地使用它们。所以我用这个替换了 UIView 动画代码:

[UIView animateWithDuration:0.2 animations:^{
    highlightView.alpha = 1.0;
}];

结果:高光仍按预期淡入,但如果我在动画完成之前 触摸,我的 touchesEnded not 会被调用。如果我在动画完成后 触摸,我的 touchesEnded 确实 会被调用。这是怎么回事?

【问题讨论】:

  • 手指,对不起。释放 = 修饰

标签: iphone objective-c cocoa-touch uiview core-animation


【解决方案1】:

iOS 4 中的新动画块默认禁用用户交互。您可以传入一个选项以允许视图在动画期间使用位标志以及UIViewanimateWithDuration:delay:options:animations:completion 方法来响应触摸,如下所示:

UIViewAnimationOptions options = UIViewAnimationOptionCurveLinear | UIViewAnimationOptionAllowUserInteraction;

[UIView animateWithDuration:0.2 delay:0.0 options:options animations:^
{
    highlightView.alpha = 1.0;
} completion:nil];

Documentation

【讨论】:

  • 刚刚编辑了我的答案——我相信您也可以将nil 作为completion: 参数传递,而不是一个空块。
  • 如果您使用 iOS SDK 5 构建,我认为这不再是必要的,但我不完全确定。对于仍在为 iOS 4 部署的任何人,我将在这里留下我的答案。
  • 所以你是说这两者对于 iOS 5+ 是等价的?
【解决方案2】:

还有一点,Apple不推荐使用[UIView beginAnimations:context:],可以在beginAnimationsdocs找到它

不鼓励在 iOS 4.0 及更高版本中使用此方法。你应该使用 使用基于块的动画方法来指定您的动画。

Apple 可能会在未来的版本中将旧方法标记为已弃用并且不会支持它们,因此使用基于块的方法确实是执行动画的更可取的方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 2011-06-07
    • 2011-12-11
    • 2010-12-03
    • 1970-01-01
    相关资源
    最近更新 更多