pikovayadama
pikovayadama

Reputation: 828

loading a custom UIView from a nib either causes an infinite loop or throws a nil exception

I have created a custom view (ImageAndToolBarContainerView) with a corresponding XIB file that I would like to load into multiple UIViewControllers in my app.

I have been hunting for a proper tutorial of how to do this, but almost every one I've come across either is too old or causes major exceptions.

When I try loading it through the story board / NIB, (I create a view in the UIViewController on the storyboard and I set the "Class" attribute to ImageAndToolBarContainerView. I Set the outlets, including the View, but none of them seem to load when the class is called, and I get the error :

fatal error: unexpectedly found nil while unwrapping an Optional value

when I try to access the view:

required init?(coder aDecoder: NSCoder)
{
    super.init(coder: aDecoder)
    //setup()
    self.view.frame = self.bounds
    self.addSubview(view)
}

Then, I try using the following code to load the NIB instead (by uncommenting the setup() function above. The code of setup is this:

func setup()
{
    self.loadViewFromNIB()
    self.view.frame = self.bounds
    self.addSubview(view)
}

func loadViewFromNIB() -> UIView
{
    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: "ImageAndToolBarContainer", bundle: bundle)
    let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
    return view
}

That of course leads to an infinite loop.

I also have the following function declares:

override func awakeFromNib()
{
    super.awakeFromNib()
    self.view.frame = self.bounds
    self.addSubview(view)
}

What am I missing here? Where did I go wrong? Is there a definitive tutorial in how to do this properly?

Upvotes: 1

Views: 1263

Answers (2)

M3nd3z
M3nd3z

Reputation: 316

For anyone having this issue, if you register a Nib for a table or collection view, you are telling that parent view to go and load a nib named 'x' whenever it needs to dequeue a cell.

Normally with Nib code, you'll want a method to go and load the actual XML that makes your layout to tie it to the Nib class, but when you register a reusable view, your registration means that the parent view is responsible for doing this. It will literally go and load an XML file for you and try and tie that to a class when you cast it. By adding another loadViewFromNIB call inside of this will then cause an infinite loop to happen.

All you need to do is set the cell Nib's class to your custom class, register it and it will do the rest for you with reusable cells - remove the loadViewFromNIB method from any initialisers inside your cell and add registration code on the collection or table view class.

Upvotes: 0

0xT0mT0m
0xT0mT0m

Reputation: 656

The infinite loop is probably caused because you set the File's Owner and also subclassed the View's class to your View's class name.

Upvotes: 2

Related Questions