user2649189
user2649189

Reputation:

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?

I tried a lot of things, but it is not compiled.

Method menuButtonAction() from OtherClass

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)  

Upvotes: 2

Views: 2261

Answers (3)

Alex Zanfir
Alex Zanfir

Reputation: 573

SWIFT 2.2 or newer:

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) {
       // ...
    }

Upvotes: 3

Akash Raghani
Akash Raghani

Reputation: 557

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")
}

Upvotes: 0

Yury
Yury

Reputation: 6114

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

Try this instead:

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

Upvotes: 0

Related Questions