【问题标题】:Swift UIWebView Delegate use and override shouldStartLoadWithSwift UIWebView 委托使用和覆盖 shouldStartLoadWith
【发布时间】:2017-03-16 17:37:26
【问题描述】:

我正在编写一个可重用的 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
       }
}

【问题讨论】:

    标签: swift3 uiwebview uiwebviewdelegate


    【解决方案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。)

    【讨论】:

    • 我需要我的 super 优先于可能测试许多字符串的孩子。具体来说,它需要在加载的 Web 视图中检查登录链接。
    • 为了让你的超级优先,你不能简单地说return super.webView(...) || load吗?
    • 好的,对于许多字符串测试,我可以将负载创建为 var,然后按照您的建议进行操作?
    • 我刚刚在答案中添加了多个字符串的示例代码,以使其更具可读性。
    • 如果 super 返回 true,则页面将加载。如果它返回 false,您的子类将决定页面是否会加载。如果您不想在 super 返回 false 时加载页面,请使用逻辑与而不是或:return superWantsToLoad && ...。还是我误会了你?
    猜你喜欢
    • 2015-06-26
    • 2015-10-28
    • 1970-01-01
    • 2018-11-20
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多