Explicitly disabling UIView animation in iOS4+

2020-02-28 02:02发布

问题:

I have been reading that Apple recommends to use block-based animations instead of CATransaction

Before, I was using this code to disable animations:

[CATransaction begin];
[CATransaction setDisableActions: YES];
// !!! resize
[CATransaction commit];

Is there a new recommended method to do this, or is this still okay?

回答1:

[UIView setAnimationsEnabled:NO];
//animate here
[UIView setAnimationsEnabled:YES];


回答2:

For iOS 7 and above this can now be accomplished with:

[UIView performWithoutAnimation:^{
    // Changes we don't want animated here
    view.alpha = 0.0;
}];


回答3:

Swift 3+

UIView.performWithoutAnimation {
            // Update UI that you don't want to animate
        }


回答4:

For MonoTouch (C#) users, here is a helper class:

public class UIViewAnimations : IDisposable
{
    public UIViewAnimations(bool enabled)
    {
        _wasEnabled = UIView.AnimationsEnabled;
        UIView.AnimationsEnabled = enabled;
    }

    public void Dispose()
    {
        UIView.AnimationsEnabled = _wasEnabled;
    }

    bool _wasEnabled;
}

Example:

using (new UIViewAnimations(false))
    imageView.Frame = GetImageFrame();


回答5:

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