2

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
    }

}

}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

is there any other way to change colors of both?
You can change the colors of both inside your method that takes a single argument. Just check which button was the sender, then change it and the other button accordingly. (Or, if you're just toggling between two colors on both buttons, you don't even have to check the sender.)
Make your button and button2 properties instead of local variables, and then you can access them in pressButton() and pressButton2().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.