[英]How to change Color of button2 in swift when button1 is clicked?
All I want to do is change the backgroundColor
of fiveMinButton and tenMinButton when fiveMinButton is clicked. 所有我想要做的是改变
backgroundColor
fiveMinButton和tenMinButton的点击fiveMinButton时。 Why doesn't this code work? 为什么此代码不起作用?
@IBAction
will not work either. @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
}
}
You are writing the action method inside the viewDidload, Try this: 您正在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
}
}
There is 2 problems with your code. 您的代码有2个问题。
selector
is wrong selector
的语法错误 viewDidLoad
that will also wrong, so write that method outside the viewDidLoad
as class method. viewDidLoad
内添加了按钮操作,这也会出错,因此请在viewDidLoad
外部将该方法编写为类方法。 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
. 对于第二个问题,只需在
viewDidLoad
写动作。
If button type rounded rect ..Color cannot be applied. 如果按钮类型为圆角rect..Color,则无法应用。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.