IBDesignable crash when trying to instantiate nib

My custom view has some code like the following:

@IBDesignable
class ABCMyView: UIView {
    // (IBOutlets and other code omitted)

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    private func commonInit() {
        let nib = UINib(nibName: "ABCMyViewContents", bundle: NSBundle.mainBundle())
        let view = nib.instantiateWithOwner(self, options: nil).first as! UIView
        addSubview(view)
    }
}

      

When trying to view ABCMyView in Interface Builder, it will crash. Attempting to debug the crash reveals that it crashes on a line that is trying to instantiate the tip with the owner. There is no error message, only a stack trace that ends with the assembly code (libobjc.A.dylib`objc_exception_throw :).

Here are some things I've tried in the console on the exception breakpoint:

(lldb) po nib
<UINib: 0x78ef8f20>


(lldb) po nib.instantiateWithOwner(self, options: nil)
error: Execution was interrupted, reason: breakpoint 1.1.
The process has been returned to the state before expression evaluation.

      

When I run the app everything works fine, only when I try to see the UIView in the interface builder.

How to load Nib file from IBDesignable?

+3


source to share


1 answer


It looks like there is a problem with the NSBundle in use. I was able to fix the problem by changing NSBundle.mainBundle()

to NSBundle(forClass: self.dynamicType)

.



I got an idea from this blog post: Subclass IBDesignable UIView with code from XIB file in Xcode 6 .

+3


source







All Articles