2016-11-04 6 views
2

pressButton2関数にbuttonとbutton2をどのように送ることができますか? ボタン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

UIButtonのような)UIControlの行動には引数、または単一の引数(アクション発火のコントロール)のいずれかをとらない方法であることがあります。 2つのボタンを使用するボタンは使用できません。なぜなら、ボタンは他の引数が何であるかわからないからです。しかし、エラーメッセージはあまり役に立ちません。

+0

両方の色を変更する方法はありますか? – Koem

+0

メソッド内で、単一の引数をとる両方の色を変更することができます。どのボタンが送信者であるかを確認し、それに応じて他のボタンを変更してください。 (または、両方のボタンで2つの色を切り替えるだけの場合は、送信者を確認する必要はありません) – NRitH

+0

しかし、私のコードにどのように実装できますか? – Koem

関連する問題