点击button1时如何更改button2的颜色?
所有我想要做的是当点击五个button时,改变五个button的backgroundColor
颜色和十个button。 为什么这个代码不工作? @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 } }
你的代码有两个问题。
-
selector
的语法是错误的 - 你已经在
viewDidLoad
中join了你的button的动作,这也是错误的,所以把这个方法写在viewDidLoad
之外作为类的方法。
对于第一个这样的变化select器。
fiveMinButton.addTarget(self, action: #selector(action(sender:)), for: UIControlEvents.touchUpInside)
对于第二个问题,只需在viewDidLoad
旁边写出操作即可。
你正在编写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 } }
如果buttontypes圆angular矩形..颜色不能应用。 所以设置button键入自定义和好去
self.myButton.backgroundColor = UIColor.redColor()
或者您可以将背景图像或图像设置为button来获取颜色
self.myButton.setBackgroundImage(UIImage.imageNamed("myButtonImage.png"), forState: UIControlStateNormal)
要么
self.myButton.setImage(UIImage.imageNamed("myButtonImage.png"), forState: UIControlStateNormal)