Alex Alex - 4 months ago 7
Swift Question

How to create a Refresh and Stop for a single UIBarbutton

I am having a

webView
where i need to display refresh/stop for single Button that need to change vice versa. when user click refresh the button need to display stop icon until the
webView
finish loads and display back refresh icon after loading the view.I need and approach to create it.

Answer

You can try something like this first declare one global button like this

var button: UIButton = UIButton()

Now create one function like this

func setRefreshItem() {
    button.frame = CGRectMake(0, 0, 18, 25)
    //Set backgroundImage in button for both state Normal and selected 
    button.setBackgroundImage(UIImage(named: "Refresh"), forState: UIControlState.Normal)
    button.setBackgroundImage(UIImage(named: "Stop"), forState: UIControlState.Selected)
    button.addTarget(self, action: #selector(self.refreshWebView(_:))",forControlEvents: UIControlEvents.TouchUpInside)
    let rightItem:UIBarButtonItem = UIBarButtonItem(customView: button)
    self.navigationItem.rightBarButtonItem = rightItem
}

Now add refreshWebView method in your viewController

func refreshWebView(sender: UIButton) {
    if (sender.selected) {
        self.webView.stopLoading() 
    }
    else {
        self.webView.reload() 
    }
    sender.selected = !sender.selected
}

//Delegate method of webView
func webViewDidFinishLoad(webView : UIWebView) {
    self.buttton.selected = false
}

Also call setRefreshItem in your viewDidLoad

Comments