Instantiate view from nib throws error

Lachtan picture Lachtan · Jan 7, 2016 · Viewed 14.3k times · Source

I tried to make @IBDesignable UIView subclass following this (link) tutorial. First custom view goes fine. But when I try to make another one, I have errors. First I got failed to update auto layout status: the agent crashed and Failed to render instance of .... Somehow I started to be able to biuld and run project with these errors, but then I get new error - EXC_BAD_ACCESS ... on line let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView. Here is whole method:

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

With first custom UIView is no problem. I use same code..

enter image description here

Any ideas? Thank you

Answer

Josh Heald picture Josh Heald · Feb 29, 2016

The loadViewFromNib() method you post looks fine, you're getting the bundle correctly and specifying the nib name as a string literal, so it should find the nib. As someone else commented, there's probably something wrong with your set up of the nib instead. Here are a few things to check:

  1. You should have AdvancedCellView set as the File's Owner Custom Class in the Identity Inspector.
  2. Check that the module is correct too - usually you just want it blank.
  3. The Custom Class for the View should not be set, just leave it as the default (UIView). If you have a more descriptive name than 'View' in the sidebar, it's probably wrong.
  4. Check that you only have one top level object in the nib. The sidebar should look like this, without any other entries, when you have the View tree collapsed.

Nib hierarchy with only one top level view

N.B. This answer is related to the tutorial that the OP linked to, and not the only correct way to set up a nib.