swiftxcodeswift3custom-controlsnib

Instantiate UIView from nib causes infinite loop issue


I'm trying to use a custom view I created.

I use instantiation from nib, but it causes an infinite loop which I'm not sure how to fix. Any idea?

Here is the image of the run result:

enter image description here

And here's the code that causes the issue:

// MARK:  - Init & Setup
// Needed for IBDesignable



override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

func setup(){
    view = loadViewFromNib()
    view.frame = bounds
    view.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))
    addSubview(view)
}

func loadViewFromNib() -> UIView{
    let bundle = Bundle(for:type(of: self))
    let nib = UINib(nibName: "LoginView", bundle: bundle)         // TEST: changin bundle from bundle-> nil

    let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
    return view
}

Edit: Here's an image of the connection

enter image description here

Thanks :)


Solution

  • It is not clear from your example (please next time provide the whole file, not just parts of it), but it looks like you are trying to instantiate LoginView from itself.

    init() -> setup() -> loadViewFromNib() -> init() -> ...

    The problem is that the instantiate will call the LoginView's init() method, which will again call loadViewFromNib(). I hope you see the problem now.

    What are you trying to do with loadViewFromNib?

    Edit: In the top right corner of your second image there is a "Custom class" section. There, in the "class" field you have to provide the name of your controller (LoginViewController or something like that). This way you connect your view and controller, and you don't need that custom loadViewFromNib method that causes your problem.