Ios 单击按钮1时,如何更改swift中按钮2的颜色?
我只想在单击fiveMinButton时更改fiveMinButton和tenMinButton的背景色。为什么这个代码不起作用<代码>@iAction也将不起作用Ios 单击按钮1时,如何更改swift中按钮2的颜色?,ios,swift,button,swift3,Ios,Swift,Button,Swift3,我只想在单击fiveMinButton时更改fiveMinButton和tenMinButton的背景色。为什么这个代码不起作用@iAction也将不起作用 @IBOutlet weak var fiveMinButton: UIButton! override func viewDidLoad() { super.viewDidLoad() fiveMinButton.addTarget(self, action: Selector(("action:")), for
@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
}
}
如果要在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
}
}
如果按钮类型为rounded rect..,则无法应用颜色。因此,将按钮设置为键入custom和good to go
self.myButton.backgroundColor = UIColor.redColor()
或者您可以将背景图像或图像设置为按钮以获得颜色
self.myButton.setBackgroundImage(UIImage.imageNamed("myButtonImage.png"), forState: UIControlStateNormal)
或
您的代码有两个问题
选择器
的语法错误viewDidLoad
中添加了按钮操作,这也将是错误的,因此在viewDidLoad
之外编写该方法作为类方法李>
对于第一个选项,请更改如下选择器
fiveMinButton.addTarget(self, action: #selector(action(sender:)), for: UIControlEvents.touchUpInside)
对于第二个问题,只需将操作写在
viewdiload
一侧,将==
更改为==
。应用程序仍在崩溃。错误日志:发送到实例的未识别选择器
是否使用swift 3?@Mr.UB您的选择器语法仍然错误添加
作为操作
方法中的第一个参数,或者使用#选择器(操作(发送方:))更改选择器,选择哪个swift版本?fiveMinButton.addTarget(self,操作:#选择器(操作(发送方:)),for:UIControlEvents.touchUpInside)
是正确的语法。修正了我的解决方案欢迎伴侣:)第3点不正确。使用==
是正确的,因为检查发送者
和五分钟按钮
是否是相同的参考。
fiveMinButton.addTarget(self, action: #selector(action(sender:)), for: UIControlEvents.touchUpInside)