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

早过忘川 提交于 2019-12-24 00:32:45

问题


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:


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.



来源:https://stackoverflow.com/questions/40425480/how-to-send-multiple-buttons-in-button-addtarget-action-swift3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!