Nathan C
Nathan C

Reputation: 286

how can I animate a button to fade out and then fade back in with a function using swift 3

In Xcode 8 using swift 3 I have 2 functions. When the "HideButton" function is called, it does the proper fade out animation, but when the "ShowButton" function is called, the fade in animation doesn't happen. Is there something wrong with the "ShowButton" animation function and how can I fix it?

func HideButton() {

    UIView.animate(withDuration: 0.2, delay: 0, animations: {
    self.MainButton.alpha = 0
    }, completion: { finished in
    self.MainButton.isHidden = true
    })

    Timer.scheduledTimer(timeInterval: 1.2, target: self, selector: #selector(GameViewController.ShowButton), userInfo: nil, repeats: false)

}

func ShowButton() {

    UIView.animate(withDuration: 0.2, delay: 0, animations: {
    self.MainButton.alpha = 1
    }, completion: { finished in
    self.MainButton.isHidden = false
    })

    Timer.scheduledTimer(timeInterval: 1.2, target: self, selector: #selector(GameViewController.HideButton), userInfo: nil, repeats: false)

}

Upvotes: 2

Views: 1173

Answers (1)

Faris Sbahi
Faris Sbahi

Reputation: 666

The isHidden property is set to true in your hideButton function. Hence, this will limit the button's functionality and prevent the visual changes you're attempting to present in showButton. Therefore, you'll need to make the button not hidden before the animation as opposed to in the completion handler.

Something like this:

func hideButton() {

UIView.animate(withDuration: 0.2, delay: 0, animations: {
self.MainButton.alpha = 0
}, completion: { finished in
self.MainButton.isHidden = true
})

Timer.scheduledTimer(timeInterval: 1.2, target: self, selector: #selector(GameViewController.ShowButton), userInfo: nil, repeats: false)

}

func showButton() {
self.MainButton.isHidden = false

UIView.animate(withDuration: 0.2, delay: 0, animations: {
self.MainButton.alpha = 1
}, completion: { finished in

})

Timer.scheduledTimer(timeInterval: 1.2, target: self, selector: #selector(GameViewController.HideButton), userInfo: nil, repeats: false)

}

Because the alpha will be zero at the beginning of the showButton animation you'll still get the desired visual effect despite the isHidden property being false before the animation takes place. Notice that I renamed your functions to preserve convention (funcs should be lower case)!

Upvotes: 2

Related Questions