CustomView with XIB - indefinite looping in init coder method

Viewed 1425

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?

5 Answers

You are probably getting the infinite recursion if, in your .xib file, for your new view (StorePricing) your Custom Class class type is set to your new custom class name (StorePricing). It should be set to UIView. To understand what' going on, when nib.instantiate(...) is reading the .xib and comes across the Custom Class name for your view, it calls required init?(coder aDecoder: NSCoder) to create it, and then, around it goes. Set the File’s Owner Custom Class to your custom class. This will allow you to establish Referencing Outlets from the .xib file into your code file.

Set the File’s Owner Class to your custom class.

enter image description here

Related