2016-11-04 40 views
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 
    } 

} 

} 

回答

1

UIControl S(像UIButton多個)動作必須是或者取任何參數,或一個參數(這是焙燒動作控制)的方法。你不能使用一個需要兩個,因爲按鈕不知道其他參數可能是什麼。但是,該錯誤消息不是很有幫助。

+0

是否有任何其他方式來改變顏色? – Koem

+0

您可以更改採用單個參數的方法中的兩種顏色。只需檢查哪個按鈕是發件人,然後相應地更改它和另一個按鈕。 (或者,如果您只是在兩個按鈕上的兩種顏色之間切換,則不必檢查發件人。) – NRitH

+0

但我如何將它實現到我的代碼中? – Koem

相關問題