我阅读到苹果建议使用基于块的动画而不是CATransaction。
以前,我使用以下代码禁用动画:
[CATransaction begin];
[CATransaction setDisableActions: YES];
// !!! resize
[CATransaction commit];
是否有新的推荐方法来完成这个任务,还是原来的方法仍然可行?
[UIView setAnimationsEnabled:NO];
//animate here
[UIView setAnimationsEnabled:YES];
对于 iOS 7 及以上版本,可以使用以下方法实现:
[UIView performWithoutAnimation:^{ // Changes we don't want animated here
view.alpha = 0.0;
}];
Swift 3+
UIView.performWithoutAnimation {
// Update UI that you don't want to animate
}
public class UIViewAnimations : IDisposable
{
public UIViewAnimations(bool enabled)
{
_wasEnabled = UIView.AnimationsEnabled;
UIView.AnimationsEnabled = enabled;
}
public void Dispose()
{
UIView.AnimationsEnabled = _wasEnabled;
}
bool _wasEnabled;
}
例子:
using (new UIViewAnimations(false))
imageView.Frame = GetImageFrame();
// Disable animations
UIView.setAnimationsEnabled(false)
// ...
// VIEW CODE YOU DON'T WANT TO ANIMATE HERE
// ...
// Force view(s) to layout
yourView(s).layoutIfNeeded()
// Enable animations
UIView.setAnimationsEnabled(true)
UIView
方法的问题在于,无法像使用CATransaction
方法那样进行嵌套。因此,如果您有一段禁用动画的代码块,并调用了其他禁用动画的内容 在 该代码块内部,那么动画将在代码块结束之前重新启用。 - jasongregoriareAnimationsEnabled
,然后在完成后将其恢复到原来的状态。 - Joshua Weinberg