skip to Main Content

I’m a novice at Swift. I want to create a button that changes color when pressed by the user. However, it ought to revert back to the original color when the user removes the finger from the button.

enter image description here

I tried different methods shown in tutorials but to no avail.

2

Answers


  1. import UIKit

    class ViewController: UIViewController {

    private let button: UIButton = {
        let button = UIButton()
        button.setTitle("First Time", for: .normal)
        button.backgroundColor = UIColor.red
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchDown)
        button.addTarget(self, action: #selector(buttonReleased(_:)), for: [.touchUpInside, .touchUpOutside])
        view.addSubview(button)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let buttonWidth: CGFloat = 200
        let buttonHeight: CGFloat = 50
        button.frame = CGRect(x: (view.bounds.width - buttonWidth) / 2,
                              y: (view.bounds.height - buttonHeight) / 2,
                              width: buttonWidth,
                              height: buttonHeight)
    }
    
    @objc func buttonPressed(_ sender: UIButton) {
         sender.backgroundColor = UIColor.blue
     }
    @objc func buttonReleased(_ sender: UIButton) {
        sender.backgroundColor = UIColor.red
    }
    

    }

    Login or Signup to reply.
  2. I want to create a button that changes color when pressed by the user. However, it ought to revert back to the original color when the user removes the finger from the button.

    The modern approach to doing this is to supply a background color transformer function. Since your code already has a reference to the button (firstTimeBtn) and an implementation of viewDidLoad, a simple approach is to modify your code as follows:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        firstTimeBtn.configuration = .filled()
        firstTimeBtn.configuration?.background.backgroundColorTransformer = .init { 
            [weak firstTimeBtn] in
            guard let firstTimeBtn else { return $0 }
            return firstTimeBtn.state == .highlighted ? .green : .red
        }
    }
    

    That gives you a button that’s red normally but is green while the user’s finger is tapping the button. Just change the colors to suit your desires. To set the button’s title in the same code, set its configuration?.title.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search