【问题标题】:iOS Swift Webview show image while loadingiOS Swift Webview 在加载时显示图像
【发布时间】:2016-07-10 15:27:57
【问题描述】:

我正在我的 iOS 应用程序中加载 Web 视图。

是否可以在后台加载 Webview 时显示图像?

我找到了一些适用于 Objective-C 的东西,但没有找到适用于 Swift 2.2 的东西。

如何检测 Web-View 是否完成加载?

编辑:

   func webViewDidStartLoad(webView: UIWebView!) {
    loadingView.viewWithTag(1)?.hidden = false 
    print("Webview started Loading")
    }

func webViewDidFinishLoad(webView: UIWebView!) {
loadingView.viewWithTag(1)?.hidden = true 
print("Webview did finish load")
}

来自:How to show image while page is loading in swift?

【问题讨论】:

  • 提供一些代码,你试过了
  • 编辑了我的帖子。我不明白在故事板中放置图像的位置。我的意思是我不能把它放在 webview 上?!
  • 检查我的编辑@simplesystems

标签: ios swift webview


【解决方案1】:

遵守 UIWebViewDelegate 协议并将您的视图控制器设置为 Web 视图的委托。完成加载后将调用函数 webViewDidFinishLoad(_ webView: UIWebView)。您可以在开始时将图像设置在 Web 视图上,然后在此功能中将其清除。

编辑:

我不能把它放在网络视图上,可以吗?

是的,就是这样做的。如果您将图像设置为隐藏,则不会影响用户与 Web 视图的交互。

【讨论】:

  • @simplesystems 什么意思,web 视图被替换了?如果您将图像放在 Web 视图上,然后将其设置为隐藏,您应该能够看到 Web 视图,而不是图像。这不会发生吗?
  • 如果您将 imagview 放置在情节提要中的 webview 上方.. 然后 webview 将被删除。
  • @simplesystems ???将 Web 视图拖到情节提要上。将图像拖到其上。现在移动图像,你会看到 web 视图没有被删除。如果运行程序时没有显示,可能是因为您没有设置约束。
  • ...看看我上面的解决方案
  • 是的,这是一种方法。但是您也可以在情节提要文件@simplesystems 中添加图像
【解决方案2】:

所以最后它的工作......

这是我的 Swift 2.2 解决方案

class YourViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {

    super.viewDidLoad()

    // For the Loading image: Create an ImageView programmatically and add id to the view
        let imageName = "YourPicture.png"
        let image = UIImage(named: imageName)
        let imageView = UIImageView(image: image!)
        imageView.tag = 1;
        imageView.frame = CGRect(x: 50, y: 250, width: 300, height: 100)
        view.addSubview(imageView)


      let url = "http://apple.com"

        let requestURL = NSURL(string:url)
        let request = NSURLRequest(URL: requestURL!)
        webView.delegate = self
        webView.loadRequest(request)        

    }

    func webViewDidFinishLoad(webView: UIWebView) {

       // UIWebView object has fully loaded.
      if(webView.stringByEvaluatingJavaScriptFromString("document.readyState") == "complete") {

        // Manually add a delay, showing the Webview takes some time..
        // For Swift 2.2
        let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 2 * Int64(NSEC_PER_SEC))

        dispatch_after(time, dispatch_get_main_queue()) {
        //put your code which should be executed with a delay here

           self.view.viewWithTag(1)?.hidden = true}
        }

        print("Webview did finish load")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多