Search code examples
swiftuicollectionviewcellxibuiactivityviewcontroller

How can I check popularProduct.xib file loaded into HomeViewController


In my HomeViewController have four section:

  1. Banner
  2. Popular Product
  3. New Product
  4. Old Product

All are .xib files and they are working fine.

Now I want to add ActivityIndicator in my HomeViewController

So now I want to show ActivityIndicator on HomeViewController until all the .xib's file not fully loaded in HomeViewController as .xib's ActivityIndicator should hide.

Now, the problem for me is that how can I get the confirmation about .xib's loaded to HomeViewController or not?


Solution

  • As a pretty simple direct solution, you could follow the delegation approach. So, when "Popular Product" View complete the needed process, you should fire a delegate method which will be handled by the view controller.

    Example:

    consider that in PopularProduct class you are implementing a method called doSomething() which need to get called and finish its work to hide the activity indicator from the view controller and it should send Data instance to the view controller. You could do it like this:

    protocol PopularProductDelegate: class {
        func popularProduct(popularProduct: PopularProduct, doSomethingDidPerformWith data: Data)
    }
    
    class PopularProduct: UIView {
        // ...
        weak var delegate: PopularProductDelegate?
    
        func doSomething() {
            // consider that there is much work to be done here
            // which generates a data instance:
            let data = Data(base64Encoded: "...")!
    
            // therefore:
            delegate?.popularProduct(popularProduct: self, doSomethingDidPerformWith: data)
        }
    
        // ...
    }
    

    Therefore, in ViewController:

    class ViewController: UIViewController {
        // ...
        var popularProduct: PopularProduct!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // show indicator
            popularProduct.doSomething()
        }
        // ...
    }
    
    extension ViewController: PopularProductDelegate {
        func popularProduct(popularProduct: PopularProduct, doSomethingDidPerformWith data: Data) {
            print(data)
            // hide indicator
        }
    }
    

    Furthermore, you could check my answer for better understanding for delegates.