如何在button.addTarget动作中发送多个按钮? Swift3

时间:2016-11-04 14:43:21

标签: swift function button swift3

如何将button和button2发送到我的pressButton2功能? 当用户触摸button2时,我需要更改按钮和按钮2的颜色...

当我的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 个答案:

答案 0 :(得分:1)

UIControl s(如UIButton s)动作必须是一个不带参数或单个参数(触发动作的控件)的方法。你不能使用两个,因为按钮不知道另一个参数可能是什么。但是,错误消息并不是非常有用。