27

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.

thumbtackthief
  • 6,093
  • 10
  • 41
  • 87
Zach Fuller
  • 1,219
  • 2
  • 14
  • 18
  • Possible duplicate of [How to disable the highlight control state of a UIButton?](http://stackoverflow.com/questions/2259905/how-to-disable-the-highlight-control-state-of-a-uibutton) – ldindu Jul 22 '16 at 23:06

12 Answers12

69

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()
}
Aleksey Potapov
  • 3,683
  • 5
  • 42
  • 65
Anubhav Singh
  • 905
  • 6
  • 5
  • 1
    Awesome! Exactly what I was after - change of opacity upon button pressed and return to normal opacity after 2sec. Thanks! – marika.daboja Mar 19 '20 at 23:26
  • 11
    Coming from Angela Yu's Udemy Swift Course, I noticed this snipped includes code from the course that is completely irrelevant to the asked question. Playing sounds does not have anything to do with changing the opacity of the button. – Henry Aug 03 '21 at 17:25
  • 4
    @Henry I'm working through this course right now. I guess I'm getting the .2 second delay for free with this answer too! – PhilCowan Sep 22 '21 at 03:27
  • 2
    Ahh, my man directly came straight to StackOverFlow form Angela Yu udemy course – Aayush Shah Dec 04 '21 at 10:54
  • Relax Henry, your getting two for the price of one on this deal! – stromyc Aug 04 '22 at 15:16
  • hey Henry, the original question was answered, and to add to it he solved some other important problem, thanks for the answer. – Afolayan Ademola Oct 19 '22 at 06:31
20

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
        }
    }
}
TomAshTee
  • 249
  • 2
  • 5
9

If you want to change the opacity you should use this code below. The alpha is basically the opacity. You can actually change the bottom part time, like how long you want it to be dimmed, you can also change sender.alpha value, like how dim you want it to be.

@IBAction func keyPressed(_ sender: UIButton) 
{          
    // 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
    }
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Pairie Koh
  • 107
  • 1
  • 4
7

I don't like a lot of these answers because they shortcut making the user think the button changes color when they tap it but only mimic a functionality apple has already provided for us. In my mind the optimal functionality would allow the button to change its opacity only when pressed and then revert when not selected. Try this out in Swift 5:

1) Create a new swift file called SomeCustomBtn

2) Insert this code:

import UIKit

class SomeCustomBtn: UIButton {
override open var isHighlighted: Bool {
    didSet {
        alpha = isHighlighted ? 0.5 : 1.0
    }
}
}

3) Add your custom class to your buttons and iOS will automatically change your alpha based on the attribute isHighlighted!

xKobalt
  • 1,498
  • 2
  • 13
  • 19
David Dailey
  • 118
  • 1
  • 5
5

To add on to AtWork, if you want to change the opacity programmatically at any time.

button.alpha = 0.30 // Make sure to use CGFloat literals
button.alpha = 1
button.alpha = 0
2

Easiest way:

    @IBAction func keyPressed(_ sender: UIButton) {
        sender.alpha = 0.5
    }
thedp
  • 8,350
  • 16
  • 53
  • 95
1
      //Reduces the opacity of the Button to half (the selected Button)
             sender.alpha = 0.5
      //this line of code will help you to delay the opacity to the selected seconds
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
     //This code brings sender's opacity back to fully opaque.
           sender.alpha = 1.0
    }
1

or one easy way is without using any DispatchQueue is this:

    @IBAction func KeyDownPressed(_ sender: UIButton) {
        sender.alpha = 0.5
    }

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

Please Note: Set Event of action of func KeyDownPressed to Touch Down

1
import UIKit
import AVFoundation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    var player: AVAudioPlayer!

    @IBAction func keyPressed(_ sender: UIButton) {
        playAudio(sound: sender.title(for: .normal)!)
        sender.alpha = 0.5
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {sender.alpha = 1}
    }
    func playAudio(sound: String) {
        let url = Bundle.main.url(forResource: sound, withExtension: "wav")
        player = try! AVAudioPlayer(contentsOf: url!)
        player.play()
    }
}
James Risner
  • 5,451
  • 11
  • 25
  • 47
1

/** This code was used for Dr Angela Yu's iOS Development Udemy course. This code works when user presses any button (multiple buttons are mapped to this IBAction function). It plays a sound, decreases opacity of the button and waits for 0.2 seconds and increases the opacity of the button (to it's default value) **/

@IBAction func keyPressed(_ sender: UIButton) {
    print(sender) // This is the identity of the button that was passed by iOS to this function
    // print(sender.currentTitle)   
    playSound(soundName: sender.currentTitle!) // ! is used for null value safety

    // Challenge - changing the layer's opacity and adding a delay
    // sender.layer.opacity = 0.7 // This can be also used to change the opacity
    sender.alpha = 0.7
    // The below code uses Dispatch Queue to add a delay (from current time till 0.2 seconds passes), other methods can block the thread entirely, and the thread cannot do any other works
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
        // sender.layer.opacity = 1
           sender.alpha = 1
    }
}
0

You can just simply set adjustsImageWhenHighlighted to NO.

button.adjustsImageWhenHighlighted = NO;

Let me know if it didn't work for you.

freya
  • 459
  • 7
  • 14
AtWork
  • 1,283
  • 1
  • 14
  • 34
0

Xcode Version 14.1

import UIKit
import AVFoundation

class ViewController: UIViewController
{
    var player: AVAudioPlayer!    
    override func viewDidLoad()
    {
        super.viewDidLoad()        
    }
   
    @IBAction func keyPressed(_ sender: UIButton)
    {
        playSound(soundName: sender.currentTitle!)
        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
            }
        }
        func playSound(soundName: String)
        {
            let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
            player = try! AVAudioPlayer(contentsOf: url!)
            player.play() 
        }
    }
    
}

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 18 '23 at 03:10