0

I'm adding a reload button for iOS in-app web browser using WKWebView.reload
I tried two options, and the two options works for me the same but I want to know what is the technical correct option to use with #selector. Is it #selector(class.method) or #selector (object.method) ?

Here is the first:

let webView = WKWebView()
view = webView
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(WKWebView.reload))

and here the second one:

let webView = WKWebView()
view = webView
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView)) 

Here is the full code

import UIKit
import WebKit

class ViewController: UIViewController {

    let webView = WKWebView()

    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(WKWebView.reload))
    }
}
  • Possible duplicate of [@selector() in Swift?](https://stackoverflow.com/questions/24007650/selector-in-swift) – Cristik Mar 19 '18 at 21:22

3 Answers3

0

Your let webView = WKWebView() is creating a new instance of yours.. it won't work independently of your #selector

try it out:

func reloadWebView() {
    webView.reload()
}

your call:

navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(MyViewController.reloadWebView))
GIJOW
  • 2,307
  • 1
  • 17
  • 37
  • No it works, you can try the full code I added to my question, but first don't forget to embed your view controller in a navigation controller. –  Mar 19 '18 at 22:13
0

The function reload is not declared as @objc, therefore, it won't work as selector in swift. You may want to create a function in your ViewController and call the reload function from there.

@objc func reloadWebView() {
    webView.reload()
}

and your selector will look like this #selector(reloadWebView)

Source: https://developer.apple.com/documentation/webkit/wkwebview/1414969-reload

Raphael Souza
  • 541
  • 4
  • 11
  • No it works, you can try the full code I added to my question, but first don't forget to embed your view controller in a navigation controller. –  Mar 19 '18 at 22:12
0

Currently, my recommendation is using #selector(target.method).

When you pass self as target then, #selector(self.method), passing webView to target, then #selector(webView.method).

#selector is just an encoded ObjC method name (which does not include class name), so both #selector(ClassName.method) and #selector(object.method) should work. But you can expect a better compile-time diagnostic with #selector(target.method).

OOPer
  • 47,149
  • 6
  • 107
  • 142