I request apologies in advance in the case this question is very elemental or the answer is obvious.
I have a custom xib, that works very well when used with the storyboard interface builder. The custom xib is implemented like the classical samples you can find across the internet:
- I have a CustomView.swift class
- a CustomView.xib file.
The FileOwner of the CustomView.xib file is set to the CustomView.class. Then this xib file has a couple of outlets for the views used in the xib. Something like the following:
@IBDesignable
class CustomView: UIView {
 @IBOutlet weak var view1: UIView!
 @IBOutlet weak var view2: UIView!
    required init?(coder aDecoder: NSCoder) {
        //When loaded from storyboard.
        super.init(coder: aDecoder)
        commonInit()
    }
    override init(frame: CGRect) {
        //When loaded from code
        super.init(frame: frame)
        commonInit()
    }
    func commonInit() {
  
        if let view = Bundle.main.loadNibNamed(self.nibName, owner: self, options: nil)?.first as? UIView {
            view.frame = self.bounds
            self.addSubview(view)
            view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
   
        }
    }
func renderViews()
//A lot of stuff is done here.
}
}
As said, this works very well when using the Storyboard designer to insert the custom xib in the layout of an UIController. But I need to use the same xib on another place, and I need to instantiate and insert it programmatically in a container view multiple times.
I tried different approaches to instantiate the xib and add it as a subview of another view, for example:
class AnotherView: UIView
(...)
func instantiateXib(){
 let view = CustomView()
  self.addSubView(view)
}
}
or
  class AnotherView: UIView
    (...)
    func instantiateXib(){
    
      let nib = UINib(nibName: "CustomView", bundle: nil).instantiate(withOwner: nil, options: nil)
      let view = nib.first as! CustomView
      self.addSubView(view)
    }
    }
or many other ways that I found across the internet, but all of them end with an infinite loop, because the method init?(coder aDecoder: NSCoder) of the xib, calls the commonInit method that instantiates again an instance of the xib, and so on.
I suspect the solution is obvious, but I'm struggling to find it.
May you point me in the right direction? Thank you in advance!
