Swift UIWebView委托使用并覆盖shouldStartLoadWith
问题描述:
我正在编写一个可重用的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
}
}
答
你可以简单地用超级实施和使用逻辑或或和,取决于你想要达到什么样的结合两种:
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
。)
我需要我的超级优先于可能测试多个字符串的孩子。具体而言,它需要检查加载的Web视图中的登录链接。 – markhorrocks
为了让你的超级优先,你不能简单地说'return super.webView(...)|| load'? – thm
好吧,对于许多字符串测试,我可以创建负载作为一个变种,然后按照你的建议做? – markhorrocks