【问题标题】:Open webview link in another View Controller在另一个视图控制器中打开 webview 链接
【发布时间】:2017-07-23 14:47:14
【问题描述】:

我有一个 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];
}

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

【问题讨论】:

  • 要在 webview 上点击 url,你应该实现 uiwebview 委托并检查在“shouldStartLoadingWith”中点击 navigationType 的链接,当然不要忘记 webView.delegate = self 更多信息:developer.apple.com/documentation/uikit/uiwebviewdelegate/…
  • @RotemDoron 谢谢,但知道怎么做吗?我已经将 webview 委托设置为 self。
  • 首先你为什么要发布 webview? self.webView.delegate = nil;
  • 我已经删除了。

标签: ios objective-c webview uiviewcontroller viewcontroller


【解决方案1】:

从 UIWebview 委托,您应该使用“shouldStartLoadWith”并检查 navigationType 是否为 linkClicked:

    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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    相关资源
    最近更新 更多