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)
}
4

3 Answers 3

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.

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

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.