我想要做的就是在点击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
}
}
答案 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个问题。
selector
的语法错误viewDidLoad
内添加了按钮的操作也会出错,因此请将该方法写在viewDidLoad
之外作为类方法。 对于这样的第一个更改选择器。
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)