1

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")
}
Sucrenoir
  • 2,994
  • 1
  • 27
  • 31
  • It's not clear where the code above is running, but you need to pass the instance of `X` as the target and your selector syntax isn't right (it's not a String): `transparentButton.addTarget(instanceOfX, action:#selector(X.closeAll), for: .touchUpInside)` – vacawama Dec 19 '17 at 17:33
  • Thx for your answer. I tried transparentButton.addTarget(self, action:#selector(X.closeAll), for: .touchUpInside) without success. C.closeAll is still getting called. – Sucrenoir Dec 19 '17 at 17:41
  • Are you assigning the instance of X to a property of C? – vacawama Dec 19 '17 at 17:53
  • No i don't. Actually X is part of a small framework and i want the implementation ans use of the class as simple as possible. – Sucrenoir Dec 20 '17 at 09:10

2 Answers2

0

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

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

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
}
0-1
  • 702
  • 1
  • 10
  • 30