Search code examples
iosswift2selectoraddtarget

Adding a target to a selector belonging to a different object


I have a UIViewController like this:

import UIKit
import WebKit

class ViewController: UIViewController {

  var webView: WKWebView?
  var backButton: UIButton?

  override func loadView() {
    self.webView = WKWebView()

    self.backButton = UIButton(type: .system)
    self.backButton?.addTarget(self.webView, action: #selector(goBack), for: .touchUpInside)
  }
}

This code attempts to connect the tapping of the back button to the WKWebView's goBack() instance method. Notice that I've passed self.webView to the button's addTarget() call.

This results in a compilation error: "Use of unresolved identifier 'goBack'". I thought the Swift compiler would be able to resolve goBack() to the WKWebKit instance.

The only way I can get this to compile is to pass in self and forward the goBack() call manually:

override func loadView() {
    self.webView = WKWebView()

    self.backButton = UIButton(type: .system)
    self.backButton?.addTarget(self, action: #selector(goBack), for: .touchUpInside)
  }

and

func goBack() {
  self.webView?.goBack()
}

Am I missing something obvious here?


Solution

  • You can just qualify your selector:

    #selector(self.webView.goBack)