UIButton in Swift 2.2。如何添加不同的目标?

时间:2016-06-09 11:42:27

标签: ios swift uiview uibutton swift2

我在代码中创建了按钮。

        let item = UIButton()
        item.setImage(UIImage(named: "Menu"), forState: .Normal)
        view.addSubview(item)

如何从其他VC添加目标?

我尝试了很多东西,但没有编译。

来自OtherClass的方法menuButtonAction()

错误:

        item.addTarget(otherClassVar, action: #selector(OtherClass.menuButtonAction), forControlEvents: .TouchUpInside)
        item.addTarget(otherClassVar, action: #selector(OtherClass.menuButtonAction(_:)), forControlEvents: .TouchUpInside)

该方法调用选择器立即:

        item.addTarget(otherClassVar, action: Selector(OtherClass.menuButtonAction()), forControlEvents: .TouchUpInside)  

3 个答案:

答案 0 :(得分:3)

SWIFT 2.2或更新版本:

yourButton.addTarget(self, action: #selector(TheClassName.runThis(_:)), forControlEvents: UIControlEvents.TouchUpInside)

我想很明显,您要运行的函数必须在要运行它的类中实现。希望很清楚。

func runThis(sender: AnyObject) {
       // ...
    }

答案 1 :(得分:0)

您正在尝试将menuButtonAction设置为static/class选择器,但我认为实际上它是实例方法,因为它未标记为static/class关键字

请改为尝试:

item.addTarget(otherClassVar, action: #selector(otherClassVar.menuButtonAction), forControlEvents: .TouchUpInside)

答案 2 :(得分:0)

希望它能帮到你......

let button   = UIButton(type: UIButtonType.RoundedRect) as UIButton
    button.frame = CGRectMake(20, 20, 100, 150)
    button.backgroundColor = UIColor(red:125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0)
    button.setTitle("Test Button", forState: UIControlState.Normal)//Highlighted here you can change state....
    button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
    self.view.addSubview(button)

然后调用函数....

func buttonAction(sender:UIButton!)

{
       print("welcome to swift 2.2")
}