2017-03-16 111 views
0

我正在编写一个可重用的UIWebView控制器,并希望从使用委托shouldStartLoadWith函数并重写它,但我不知道如何去做。Swift UIWebView委托使用并覆盖shouldStartLoadWith

在我可重用的UiWebView控制器我有这个。

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

    let docURLStr = request.mainDocumentURL!.absoluteString 

    if docURLStr.contains("login") { 
     loadLoginView() 
     return false 
    } 

然后在我的子类中我想要做以下但我想使用这两个函数。我该怎么做?

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

let docUrl = request.url!.absoluteString 

if String(describing: docUrl).range(of: "some string in the url") != nil{ 
    return true 
    } else { 
     return false 
     } 
} 

回答

1

你可以简单地用超级实施和使用逻辑或或和,取决于你想要达到什么样的结合两种:

override func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool 
{ 
    let docUrl = request.url!.absoluteString 
    let load = String(describing: docUrl).range(of: "some string in the url") != nil 
    return load || super.webView(webView, shouldStartLoadWith: request, navigationType: navigationType) 
} 

要检查几串你可能会做这样的事情这样的:

override func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool 
{ 
    let docUrl = request.url!.absoluteString 
    let superWantsToLoad = super.webView(webView, shouldStartLoadWith: request, navigationType: navigationType) 
    let strings = ["foo", "bar"] 
    return superWantsToLoad || strings.contains(where: { docUrl.contains($0) }) 
} 

请注意string.contains()通话将仅superWantsToLoad是假的由于短路评价评估。 如果你有很多字符串需要处理,这可能很重要。 (或者,您可以插入早期return true。)

+0

我需要我的超级优先于可能测试多个字符串的孩子。具体而言,它需要检查加载的Web视图中的登录链接。 – markhorrocks

+0

为了让你的超级优先,你不能简单地说'return super.webView(...)|| load'? – thm

+0

好吧,对于许多字符串测试,我可以创建负载作为一个变种,然后按照你的建议做? – markhorrocks