Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 580
Shefy Gur-ary Avatar asked Oct 30 '25 11:10

Shefy Gur-ary


1 Answers

Quick answer: Since the top-level view in the Xib had its custom class set to YourCustomeView, the xib loading process loadViewFromNib will then call your initWithCoder method again ⛔️🚫♽.

Quick fix: In the Xib, instead of setting the custom class of the view as YourCustomeView, set YourCustomeView as The File Owner of the Xib.

More info https://medium.com/@anandin02/loading-custom-views-in-ios-the-right-way-bedfc06a4fbd

like image 81
Dania Delbani Avatar answered Nov 01 '25 13:11

Dania Delbani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!