简体   繁体   中英

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

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.

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM