如何为单个 UIBarbutton 创建刷新和停止

How to create a Refresh and Stop for a single UIBarbutton

我有一个 webView,我需要为单个按钮显示 refresh/stop,反之亦然。当用户单击刷新按钮时需要显示停止图标,直到 webView 完成加载并在加载后显示返回刷新图标 view.I 需要和创建它的方法。

有几种不同的方法可以做到这一点。您可以在 ViewController 中声明另一个名为 "allowsRefresh" 的变量,然后当您单击该按钮时,您可以执行类似

的操作
@IBAction refreshOrStop(sender: AnyObject) {
    if (allowsRefresh) {
        // Do stuff that refreshes the webpage
    } else {
        // Do stuff that stops the refresh
    }
    allowsRefresh = !allowsRefresh 
    // Inverse itself. If it was true, change it false. If it was false, change it to true
}

肯定有比 allowsRefresh 更好的名称,但您明白了。

你可以尝试这样的事情,首先像这样声明一个全局按钮

var button: UIButton = UIButton()

现在创建一个这样的函数

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
}

现在在您的 viewController

中添加 refreshWebView 方法
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
}

也可以在 viewDidLoad

中调用 setRefreshItem