3

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?

RobertJoseph
  • 7,968
  • 12
  • 68
  • 113

1 Answers1

10

You can just qualify your selector:

#selector(self.webView.goBack)
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • Then should the first argument of addTarget() still be `self.webView`, or should it just be `self`? – arlomedia Dec 10 '20 at 08:14
  • 1
    @arlomedia It would be the `webView`. In message-passing terms, `self.webView` would be the *receiver* of the message identified by the selector `#selector(self.webView.goBack)`. When that message is sent to `self.webView`, clicking your button would send it message `goBack`, which `self` doesn't respond to. – Alexander Dec 10 '20 at 13:26