单击button1时如何更改swift中button2的颜色?

时间:2016-09-23 04:37:53

标签: ios swift button swift3

我想要做的就是在点击fiveMinButton时更改fiveMinButton和tenMinButton的backgroundColor。为什么这段代码不起作用? @IBAction也无效。

@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 个答案:

答案 0 :(得分:1)

您正在viewDidload中编写action方法,试试这个:

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

答案 1 :(得分:1)

您的代码存在2个问题。

  1. selector的语法错误
  2. 您已在viewDidLoad内添加了按钮的操作也会出错,因此请将该方法写在viewDidLoad之外作为类方法。
  3. 对于这样的第一个更改选择器。

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

    对于第二个问题,只需在viewDidLoad旁边写下操作。

答案 2 :(得分:0)

如果按钮类型为圆形rect ..Color无法应用。因此,将按钮设置为自定义,然后设置好

self.myButton.backgroundColor = UIColor.redColor()

或者您可以将背景图像或图像设置为按钮以获得颜色

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

self.myButton.setImage(UIImage.imageNamed("myButtonImage.png"), forState: UIControlStateNormal)
相关问题