Alex Alex - 1 year ago 80
Swift Question

How to create a Refresh and Stop for a single UIBarbutton

I am having a

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
finish loads and display back refresh icon after loading the view.I need and approach to create it.

Answer Source

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) {
    else {
    sender.selected = !sender.selected

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

Also call setRefreshItem in your viewDidLoad

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download