4

I Have Already made the Outlets and the action. I have linked the code to the UI.

I want a button to be highlighted when pressed. This the code I wrote:

 @IBAction func buttonPressed(_ sender: UIButton) {
        sender.setTitleColor(UIColor(GL_GREEN), for: .highlighted)
}
WebDevBooster
  • 14,674
  • 9
  • 66
  • 70
  • https://stackoverflow.com/questions/14523348/how-to-change-the-background-color-of-a-uibutton-while-its-highlighted – iDeveloper Feb 20 '18 at 07:44
  • @IBAction func buttonPressed(_ sender: UIButton) { sender.tintColor = UIColor.green for sub in view.subviews { if sub.isKind(of: UIButton.self) { if sub != sender { sub.tintColor = UIColor.black } } } } – El Tomato Feb 20 '18 at 07:49
  • Possible duplicate of [How to highlight a custom UIButton that has no text or background?](https://stackoverflow.com/questions/48620402/how-to-highlight-a-custom-uibutton-that-has-no-text-or-background) – Tamás Sengel Feb 20 '18 at 16:37
  • Did my answer help or do you need more assistance? – whoswho Feb 22 '18 at 09:11

3 Answers3

12

You can subclass a UIButton. Create a new swift file and name it anything you want but in this example I will name it HighlightedButton. Add below code in the new file you created. The class is named same as the file you created.

import UIKit

class HighlightedButton: UIButton {

    override var isHighlighted: Bool {
        didSet {
            backgroundColor = isHighlighted ? .red : .green
        }
    }
}

Next step is to set HighlightedButton as the class of your button:

In storyboard choose the UIButton you want to change. In the identity inspector in the right corner there is a filed named "class" there type "HighlightedButton" and press enter. Now your button will change color to red when it is highlighted and back to green when you release the button.

You can change to any color you want.

whoswho
  • 202
  • 1
  • 10
5

You have to make 2 actions one is "Touch down" and "Touch up inside" action . change background color for both of the action and you will achieve your target

Ajay Vyas
  • 81
  • 7
2

In 2021...

You just need to set the ButtonType to be .system and it will highlight when pressed.

let button = UIButton(type: .system)

Here's a button I made, for clarity:

lazy var myButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Show More", for: .normal)
        button.setTitleColor(.systemBlue, for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 17, weight: .regular)
        button.layer.masksToBounds = true
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        return button
}()
    
@objc fileprivate func buttonTapped() {
        //code for segue
}
Henry Noon
  • 334
  • 3
  • 7