Back Button on UIWebView

时间秒杀一切 提交于 2019-12-06 21:24:22

问题


I'm trying to figure out how to create a back button that allows the user to go back one page. I read through Apple's Docs (which still go way over my head) and found out that I need to setup the canGoBack and goBack's. I have tried this, but for some reason it is not working. My UIWebView is named viewWeb, and I created and attached an outlet to my Back button, named backButton, and also tagged it as 1. Here is my code that I wrote in the View Controller:

// Back button:
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {

        [_backButton addTarget:_viewWeb
                         action:@selector(goBack)
               forControlEvents:UIControlEventTouchDown];

        if ([_viewWeb canGoBack]) {

            NSLog(@"Back button pressed.");
            [_viewWeb goBack];
        }
    }

    else return;
}

Does anyone know what I need to change / add to get this working?


回答1:


actionSheet:clickedButtonAtIndex: is for UIActionSheet objects, not UIButton actions.

You should probably write an IBAction method that looks something like this:

- (IBAction)backButtonTapped:(id)sender {
   [_viewWeb goBack];
}

and connect it to the Touch Up Inside action from the button.

You can search for more info on IBAction but that's likely what you want




回答2:


I think it should be more specific like this

- (IBAction)backButtonTapped:(id)sender {
   if ([_viewWeb canGoBack] ) {
       [_viewWeb goBack];
   }
}



回答3:


I have struggled to get a working code for this function written in swift and finally here's what i came up with.

 @IBOutlet weak var goBackBtn: UIBarButtonItem!
 @IBOutlet weak var goForwardBtn: UIBarButtonItem!
 @IBOutlet weak var itemWebView: UIWebView!

 override func viewDidLoad() {
    super.viewDidLoad()

    let url = NSURL (string: "www.google.com")
    let requestObj = NSURLRequest(URL: url)
    itemWebView.loadRequest(requestObj)

    itemWebView.delegate = self


    goBackBtn.enabled = false
    goForwardBtn.enabled = false
}


func webViewDidFinishLoad(webView: UIWebView) {
    goBackBtn.enabled = itemWebView.canGoBack
    goForwardBtn.enabled = itemWebView.canGoForward  
}

@IBAction func forward(sender: AnyObject) {

    itemWebView.goForward()

}


@IBAction func back(sender: AnyObject) {
     itemWebView.goBack()
}



回答4:


For swift 4 and swift 5

@IBAction func refreshAction(_ sender: Any) {
    self.webView.reload()
}

@IBAction func backAction(_ sender: Any) {
    if(self.webView.canGoBack) {
        self.webView.goBack()
       }
}

@IBAction func forwardAction(_ sender: Any) {
    if self.webView.canGoForward{
        self.webView.goForward()
    }
}


来源:https://stackoverflow.com/questions/16704950/back-button-on-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!