Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight a button when Pressed In swift

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)
}
like image 383
Everything about Tech Pro Avatar asked Dec 01 '22 14:12

Everything about Tech Pro


1 Answers

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.

like image 105
whoswho Avatar answered Dec 05 '22 18:12

whoswho