在另一个视图控制器中打开 webview link

Open webview link in another View Controller

我有一个 webview,我想在另一个 ViewController 中打开我可以在该 webview 中单击的 url,例如更改导航栏并添加后退按钮。

这是我在 objective-c 中的当前代码:

    - (void)viewDidLoad {
        [super viewDidLoad];

        NSString *fullURL = @"https://www.apple.com/";
        NSURL *url = [NSURL URLWithString:fullURL];
        NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
        self.webView.delegate = (id)self;
        [self.webView loadRequest:requestObj];

        UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
        [refreshControl addTarget:self action:@selector(handleRefresh:) forControlEvents:UIControlEventValueChanged];
        refreshControl.tintColor = [UIColor clearColor];
        [self.webView.scrollView addSubview:refreshControl];



    }

-(void)handleRefresh:(UIRefreshControl *)refresh {
    NSString *fullURL = @"https://www.apple.com/";
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:requestObj];
    [refresh endRefreshing];
}

有什么解决办法吗? 谢谢!

从 UIWebview 委托中,您应该使用 "shouldStartLoadWith" 并检查 linkClicked 的 navigationType:

    func webView(_ webView: UIWebView,
             shouldStartLoadWith request: URLRequest,
             navigationType: UIWebViewNavigationType) -> Bool {

    if navigationType == .linkClicked{
        if let url = URL(string:"YourURLString") {
            if UIApplication.shared.canOpenURL(url){
                UIApplication.shared.openURL(url)
                return false
            }
        }
    }

    return true
}

可以在此处找到有关 uiwebview 委托的更多信息: https://developer.apple.com/documentation/uikit/uiwebviewdelegate/1617945-webview