简体   繁体   中英

How to change the background color of a UIButton when tapped in swift?

ViewController: UIViewController {
   @IBAction func like(sender: AnyObject) {
       like(backgroundColor!) = UIColor.greenColor()
   }
}

I want to chanage the color of UIbutton"like button" : White is the default "not tapped or unlike" green when is tapped.

How do you change a buttons background colour when it is tapped using Swift?

The button isn't like -- that's the method's name. You can access the button through sender .

@IBAction func like(sender: AnyObject) {
    (sender as UIButton).backgroundColor = UIColor.greenColor()
}

Or more concise:

@IBAction func like(button: UIButton ) {
    button.backgroundColor = UIColor.greenColor()
}

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