Search code examples
iosswiftuiwebviewuicollectionviewuiwebviewdelegate

How to detect when UIWebView starts loading when Webview is inside a Collection View cell?


I am loading a collection view of cells containing UIWebViews. There's a time gap between when my UICollectionView's activity indicator stops spinning and the UIWebView loads. I am trying to get a reference to when the loading starts (and eventually when it stops) in order to add another activity indicator UI. I'm not sure how to do it here though since my UIWebView is in my CollectionViewCell and not my CollectionView, in other words I can't use the delegate methods and set myself as my delegate in my collectionViews VDL? My CollectionViewCell code:

 import UIKit
import WebKit

class SearchCollectionViewCell: UICollectionViewCell {


    @IBOutlet weak var webView: UIWebView!

    @IBOutlet weak var spinner: UIActivityIndicatorView!

    func webViewDidStartLoad(_ webView: UIWebView) {
        print("we're loading")
    }


}

Solution

  • You need to implement UIWebViewDelegate in your cell and set you cell as delegate then in the method webViewDidStartLoad you will be notified

    import UIKit
    import WebKit
    
    class SearchCollectionViewCell: UICollectionViewCell {
    
    
        @IBOutlet weak var webView: UIWebView!
    
        @IBOutlet weak var spinner: UIActivityIndicatorView!
    
        override func awakeFromNib() {
            super.awakeFromNib()
            self.webView.delegate = self
            // Initialization code
        }
    
    }
    
    extension SearchCollectionViewCell : UIWebViewDelegate
    {
        public func webViewDidStartLoad(_ webView: UIWebView) {
            debugPrint("Start Loading")
        }
    }
    

    Hope this helps