2
如何将button和button2发送到我的pressButton2函数中? 当用户点击按钮2时,我需要更改按钮和按钮2的颜色...如何在button.addTarget动作中发送多个按钮? Swift3
当我的button2.addTarget看起来像这样,我得到一个错误:'表达式列表中的预期表达式'。
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let button = UIButton(frame: CGRect(x: 10, y: 50, width: 100, height: 100))
button.backgroundColor = UIColor.gray
button.setTitle("123", for: [])
button.addTarget(self, action: #selector(pressButton(button:)), for: .touchUpInside)
////// sec button
let button2 = UIButton(frame: CGRect(x: 120, y: 50, width: 100, height: 100))
button2.backgroundColor = UIColor.gray
button2.setTitle("1234", for: [])
button2.addTarget(self, action: #selector(pressButton2(button2:, button:)), for: .touchUpInside)
self.view.addSubview(button)
self.view.addSubview(button2)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func pressButton(button: UIButton) {
NSLog("pressed!")
if button.backgroundColor == UIColor.gray {
button.backgroundColor = UIColor.red
}else{
button.backgroundColor = UIColor.gray
}
}
func pressButton2(button2: UIButton, button:UIButton) {
NSLog("pressed!")
if button2.backgroundColor == UIColor.gray {
button2.backgroundColor = UIColor.red
}else{
button2.backgroundColor = UIColor.gray
}
}
}
是否有任何其他方式来改变颜色? – Koem
您可以更改采用单个参数的方法中的两种颜色。只需检查哪个按钮是发件人,然后相应地更改它和另一个按钮。 (或者,如果您只是在两个按钮上的两种颜色之间切换,则不必检查发件人。) – NRitH
但我如何将它实现到我的代码中? – Koem