How to change Color of button2 in swift when butto

2020-04-23 06:18发布

All I want to do is change the backgroundColor of fiveMinButton and tenMinButton when fiveMinButton is clicked. Why doesn't this code work? @IBAction will not work either.

@IBOutlet weak var fiveMinButton: UIButton!



 override func viewDidLoad() {
    super.viewDidLoad()

    fiveMinButton.addTarget(self, action: Selector(("action:")), for: UIControlEvents.touchUpInside)

    func action(sender: UIButton){

        if sender === fiveMinButton {

            fiveMinButton.backgroundColor = UIColor.gray
            tenMinButton.backgroundColor = UIColor.lightgray

        }

    }

3条回答
我欲成王,谁敢阻挡
2楼-- · 2020-04-23 06:41

You are writing the action method inside the viewDidload, Try this:

override func viewDidLoad() {
    super.viewDidLoad()

    fiveMinButton.addTarget(self, action: #selector(action(_:)), for: UIControlEvents.touchUpInside)

}

func action(sender: UIButton){
        if sender == fiveMinButton {
            fiveMinButton.backgroundColor = UIColor.gray
            tenMinButton.backgroundColor = UIColor.lightgray
        }
}
查看更多
干净又极端
3楼-- · 2020-04-23 06:41

If button type rounded rect ..Color cannot be applied. So set the button to type custom and good to go

self.myButton.backgroundColor = UIColor.redColor()

or you can set the background image or image to the button to gain the color

self.myButton.setBackgroundImage(UIImage.imageNamed("myButtonImage.png"), forState: UIControlStateNormal)

or

self.myButton.setImage(UIImage.imageNamed("myButtonImage.png"), forState: UIControlStateNormal)
查看更多
家丑人穷心不美
4楼-- · 2020-04-23 06:51

There is 2 problems with your code.

  1. The syntax of selectoris wrong
  2. You have added action of your button inside the viewDidLoad that will also wrong, so write that method outside the viewDidLoad as class method.

For first one change selector like this.

fiveMinButton.addTarget(self, action: #selector(action(sender:)), for: UIControlEvents.touchUpInside)

For second problem just write action out side the viewDidLoad.

查看更多
登录 后发表回答