Button does not work in WKwebview

Button gives an error message, i dont know how to fix it. Can somebody please help? This is the error: Use of local variable 'buttonAction' before its declaration




//button

let buttonFrame = CGRect(x: 50, y: 50, width: 50, height: 40)

let button = UIButton(frame: buttonFrame)

button.backgroundColor = UIColor.black

webView.scrollView.addSubview(button)


button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)⚠


func buttonAction(sender: UIButton!) {

if webView.url != nil {

webView.reload()

} else {

webView.load(URLRequest(url:url)) //where originalURL is the URL you're initially using to show in webView

}

Replies

The problem here is that you’re declaring the

buttonAction(sender:)
method as a local function rather than a method. To understand what’s going on, you have to step out a bit. Consider your overall view controller, which might look something like this:
class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        … create `button` …

        button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)

        // B
    }

    @IBAction
    func buttonAction(sender: UIButton!) {
        …
    }
}

Note how

buttonAction(sender:)
is declared at the top level of the class. This is what makes it a method. I believe that you currently have it declared nested within the
viewDidLoad
method, that is, at line B, which makes it a function local to that method.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"