Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing opacity of button when clicked xcode / swift

Tags:

xcode

ios

swift

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.

like image 760
Zach Fuller Avatar asked Jul 22 '16 20:07

Zach Fuller


People also ask

How do I change the opacity of a clicked button in Swift?

@IBAction func KeyDownPressed(_ sender: UIButton) { sender. alpha = 0.5 } @IBAction func keyPressed(_ sender: UIButton) { sender. alpha = 1 playSound(col : sender. currentTitle!) }

How do I add a delay in Swift?

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.


2 Answers

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
        }
    }
}
like image 45
TomAshTee Avatar answered Sep 19 '22 11:09

TomAshTee


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()
}
like image 67
Anubhav Singh Avatar answered Sep 21 '22 11:09

Anubhav Singh