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