Xavier Garcia Rubio
Xavier Garcia Rubio

Reputation: 105

How to get action on button pressed in a component to viewcontroller

I've made a UIView component, inside has 2 buttons. When a user touch the buttons, I need to call a action method of ViewController.

I've tried to pass a selector, but it crash:

on ViewController

component.leftAction = #selector(ViewController.myAction)

func myAction(sender: UIButton!) {
    print("tapped!")
}

on Component.swift

public var leftAction: Selector? {
    didSet {
        if (leftAction != nil){
            self.leftButton.addTarget(self, action: leftAction!, for: .touchUpInside)
        }
    }
}

How can I do it?

Upvotes: 0

Views: 336

Answers (3)

Abhishek Jain
Abhishek Jain

Reputation: 4739

Just change

component.leftAction = #selector(ViewController.myAction)

to

component.leftAction = #selector(ViewController.myAction(sender:))

And ViewController should not be deallocated.

Upvotes: 0

Bilal
Bilal

Reputation: 19156

It's crashing because button target is wrong. In your case you are passing target as self which is an instance of Component class. Target must be your ViewController instance because your selector is defined in your ViewController class.

You can do something like this to fix your problem.

public var leftTargetAction: (Any, Selector)? {
    didSet {
        if let targetAction = leftTargetAction {
            self.leftButton.addTarget(targetAction.0, action: targetAction.1, for: .touchUpInside)
        }
    }
}    

And use it like this.

component.leftTargetAction = (self,#selector(ViewController.myAction))

Upvotes: 2

Mohammad Sadiq
Mohammad Sadiq

Reputation: 5241

Better approach would be to handle this with delegates. To know more about delegate you can go through this post.

Upvotes: 0

Related Questions