Animated display button

2019-09-07 08:33发布

问题:

I'm trying to create a basic animation. I need to touch on a button to hide or show.

I wrote this code to tap on the screen:

func visibleControlButton(_ sender: UITapGestureRecognizer) {
    if (backButton!.isHidden) {
        _UIButtonHiddenAnimation.hiddenAnimation(button: self.backButton!, hide: false)
    } else {
        _UIButtonHiddenAnimation.hiddenAnimation(button: self.backButton!, hide: true)
    }
}

Definition _UIButtonHiddenAnimation:

 class _UIButtonHiddenAnimation {
    class func hiddenAnimation(button: UIButton, hide: Bool) {
        UIView.animate(withDuration: 0.2,
                       animations: {
                            hide ? (button.alpha = 0) : (button.alpha = 1.0)
                        },
                       completion: {
                            finished in hide ? (button.isHidden = true) : (button.isHidden = false)
                        })
    }
}

Animates just hide the button. How to make an animated appearance of a button?

回答1:

The problem is that if the button is hidden, you are animating the alpha to 1 but we cannot see that — because the button is hidden! Then you set isHidden to false and the button jumps into view.

The solution: forget all about isHidden and change only the alpha — and then change your if test to match what you are doing with the button, i.e. simply test against its alpha value. Thus (neatening things up as we go):

class _UIButtonHiddenAnimation {
    class func hiddenAnimation(button: UIButton, hide: Bool) {
        UIView.animate(withDuration: 0.2, animations: {
            button.alpha = hide ? 0 : 1.0
        })
    }
}

func visibleControlButton(_ sender: UITapGestureRecognizer) {
    _UIButtonHiddenAnimation.hiddenAnimation(
        button: self.backButton!, hide: backButton!.alpha > 0.1)
}


标签: ios swift xcode