Call UIButton AddTarget in the same class

358 Views Asked by At

I have a simple view V and view controller C. The controller calls a separate class X that build a webview and a button to close the webview.

I instantiate class X (with a reference to view V) then call a method to attach both items (webview and items).

When i call the button addTarget method, it does not work. I want it to execute the closeAll method of the X class and not the closeAll method of the C controller.

I have tried hundreds of variants.

Here is (parts of) the code in C controller:

let parentView:UIView
...

@objc func closeAll() {
    print("Close webview, object")
}

and this in X class:

    ...
    let transparentButton = UIButton(frame: frame)
    transparentButton.backgroundColor = UIColor.black.withAlphaComponent(self.overlayTransparency)
    transparentButton.setTitle("", for: .normal)
    transparentButton.alpha = 0.5
    transparentButton.isUserInteractionEnabled = true
    transparentButton.addTarget(self, action:#selector("closeAll"), for: .touchUpInside)
    parentView.addSubview(transparentButton)

I have this in my C controller and it get called on click:

@objc func closeAll() {
    print("Close webview, main")
}
2

There are 2 best solutions below

1
On

Change self to instance of a class that you want it's method to be triggered

3
On

You can insert either of these into your class:

override func viewDidLoad() {  
    super.viewDidLoad()
    transparentButton.addTarget(self, action:#selector(closeAll),  for: .UIControlEvents.valueChanged)
}

func closeAll(sender:AnyObject) {
    // your code
}

OR

@IBOutlet var btnStartJob: UIButton!
override func viewDidLoad()    {  
    super.viewDidLoad()
    btnStartJob.addTarget(self, action: #selector(closeAll), for: .touchUpInside)
}

func closeAll(_ sender : UIButton) {
    // your code
}