2017-03-16 96 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