Search code examples
iosswiftuiwebviewuibutton

Overlay a refresh button over a UIWebView


I am attempting to add a button in the top right corner of my app that will reload my webView. I have attempted to follow other answers here and here, but have not had any luck getting the button to show up.

I have the following code in my ViewController class:

override func viewDidLoad() {
    super.viewDidLoad()
    let webView:UIWebView = UIWebView(frame: CGRectMake(30, 20, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
    webView.scalesPageToFit = true
    webView.multipleTouchEnabled = true
    webView.backgroundColor = UIColor.whiteColor()
    webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.example.com")!))
    self.view.addSubview(webView)
}

I would like to overlay the button. How could I add a button to reload the webView when pressed?


Solution

  • You can simply add button to your web view hierarchy e.g.

        let buttonFrame = CGRect(x: 50, y: 150, width: 50, height: 50)
        let button = UIButton(frame: buttonFrame)
        button.backgroundColor = UIColor.greenColor()
        webView.scrollView.addSubview(button) // in that way button will be scroling with webView.
    

    or add button above webView e.g.

            let buttonFrame = CGRect(x: 50, y: 150, width: 50, height: 50)
            let button = UIButton(frame: buttonFrame)
            button.backgroundColor = UIColor.greenColor()
            insertSubview(button, aboveSubview: webView)