2016-09-23 89 views
1

当我点击五个按钮时,我想要做的就是改变五个按钮和十个按钮的backgroundColor。为什么这个代码不工作? @IBAction也不起作用。如何在单击button1时快速更改button2的颜色?

@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 

     } 

    } 

回答

1

有是你的代码有两个问题。

  1. selector语法是错误的
  2. 您已经添加了您的按钮的动作viewDidLoad内,这将也是错误的,所以写的viewDidLoad之外的方法类方法。

对于第一个像这样的变化选择器。

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

对于第二个问题,只需写出viewDidLoad的行动。

+0

'fiveMinButton.addTarget(self,action:#selector(action(sender :)),for:UIControlEvents.touchUpInside)'是正确的语法。修复了我的解决方案 – grant

+0

欢迎队友:) –

+0

第3点不正确。使用'==='是正确的,因为检查是看'sender'和'FiveMinButton'是否是相同的引用。 – rmaddy

1

你正在写的viewDidLoad中内部的操作方法,试试这个:

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

仍然不起作用。 – grant

+0

将'==='改为'=='。 –

+0

应用程序仍在崩溃。错误日志:'无法识别的选择器发送到实例' – grant

0

如果按钮类型圆角的矩形..Color不能适用。因此,设置按钮,自定义类型和良好的去

self.myButton.backgroundColor = UIColor.redColor() 

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

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

self.myButton.setImage(UIImage.imageNamed("myButtonImage.png"), forState: UIControlStateNormal) 
+0

非常不好的答案。 – grant

相关问题