Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CustomView with XIB - indefinite looping in init coder method

In my project I am trying to create a custom UIView from a XIB file. I followed few tutorials and arrived at below code to load

import UIKit

class StorePricing: UIView {

    override init(frame: CGRect) {

        super.init(frame: frame)
        self.setupView()
    }

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)
        self.setupView()
    }

    private func setupView() {

        let view = self.loadViewFromXib()

        view.frame = self.bounds
        view.autoresizingMask = [.flexibleHeight, .flexibleWidth]

        self.addSubview(view)
    }

    private func loadViewFromXib() -> UIView {

        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView

        return view

    }

}

When I add this custom view in another view my app crashed and I noticed the init call is called in a indefinite loop. The call hierarchy is as follows in my custom view

  1. Call to init coder
  2. Call to setupView()
  3. Call to loadViewFromXib()

nib.instantiate calls init coder and the loop becomes indefinite

Any suggestions on how to solve this issue?

like image 654
slysid Avatar asked Dec 19 '22 05:12

slysid


1 Answers

if your xib file contains an instance of your view, then then it's loaded, it will call init(coder:), which will then load the xib file again, and the cycle will restart. I would either remove instances of your view from the xib file, or don't call setupView() from within init(coder:)

like image 141
Ben Gottlieb Avatar answered Dec 26 '22 12:12

Ben Gottlieb