I have an UIButton set up with an image and by default when the user presses the button, the image is reduced to around 30% opacity.
I am wondering how to prevent this from happening and how to set the opacity to whatever I need it to be.
@IBAction func KeyDownPressed(_ sender: UIButton) { sender. alpha = 0.5 } @IBAction func keyPressed(_ sender: UIButton) { sender. alpha = 1 playSound(col : sender. currentTitle!) }
To add a delay to your code we need to use GCD . GCD has a built in method called asyncAfter , which will allow us to run code after a given amount of time. In the above code, Before delay will be printed out first and after 2 seconds, Async after 2 seconds will be printed.
Swift 5
You can do this by using DispatchQueue. What's more, to make the transition "smooth" use UIView.animate.
Just change the alpha parameter.
@IBAction func keyPressed(_ sender: UIButton) {
sender.alpha = 0.5
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3 ) {
sender.alpha = 1.0
}
}
Smooth change of the parameter.
@IBAction func keyPressed(_ sender: UIButton) {
UIView.animate(withDuration: 0.3) {
sender.alpha = 0.5
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3 ) {
UIView.animate(withDuration: 0.3) {
sender.alpha = 1.0
}
}
}
To add on the viewController, if you want to change opacity and time delay programmatically.
@IBAction func keyPressed(_ sender: UIButton) {
playSound(soundName: sender.currentTitle!)
//Reduces the sender's (the button that got pressed) opacity to half.
sender.alpha = 0.5
//Code should execute after 0.2 second delay.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
//Bring's sender's opacity back up to fully opaque.
sender.alpha = 1.0
}
}
func playSound(soundName: String) {
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With