Koem
Koem

Reputation: 21

How to send multiple buttons in button.addTarget action? Swift3

How can I send button and button2 into my pressButton2 function? I need to change color of button and button2 when user will touch button2...

When my button2.addTarget looks like this, I got an error: 'Expected expression in list of expressions'.

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
    }

}

}

Upvotes: 2

Views: 680

Answers (1)

NRitH
NRitH

Reputation: 13903

A UIControls (like UIButtons) action has to be a method that takes either no arguments, or a single argument (the control that's firing the action). You can't use one that takes two, because the button has no idea what the other argument could possibly be. The error message isn't very helpful, though.

Upvotes: 1

Related Questions