简体   繁体   English

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

[英]UIButton in Swift 2.2. How to add different target?

I created button in code. 我在代码中创建了按钮。

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

How can I add target from other VC? 如何从其他VC添加目标?

I tried a lot of things, but it is not compiled. 我尝试了很多事情,但尚未编译。

Method menuButtonAction() from OtherClass 来自OtherClass的方法menuButtonAction()

Errors: 错误:

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

that method call selector immediately: 该方法立即调用选择器:

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

SWIFT 2.2 or newer: SWIFT 2.2或更高版本:

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

I guess is obvious that the function you want to run must be implemented in the class you want to run it from. 我想很明显,您要运行的功能必须在您要运行其的类中实现。 Hope is clear enough. 希望很明确。

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

You are trying to set menuButtonAction as static/class selector, but as I think at fact it is instance method, since it is not marked by static/class keyword 您正在尝试将menuButtonAction设置为static/class选择器,但实际上我认为它是实例方法,因为它没有用static/class关键字标记

Try this instead: 尝试以下方法:

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

hope it will help you..... 希望对您有帮助。

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)

and then call the function.... 然后调用该函数。

func buttonAction(sender:UIButton!)

{
       print("welcome to swift 2.2")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM