Search code examples
iosswiftuiviewxcode9ibdesignable

IBDesignable UI is not showing in Xcode 9 with Swift


I trying to using my custom xib files. But those UI are not showing in main view controller in xcode. But it show when run the app. I already added @IBDesignable in class. Here is what i did.

  1. I created TestView.xib and added some design

  2. I created TestView.swift

  3. I updated fileOwner of TestView.xib with TestView in Custom Class

  4. I added init code to testView.swift

Code inside TestView.swift

import UIKit

@IBDesignable class DetailView: UIView {

override init(frame: CGRect){
    super.init(frame: frame)
    self.setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    self.setup()

}

func setup() {
    let view = Bundle.main.loadNibNamed("TestView", owner: self, options: nil)?.first as! UIView
    view.frame = self.bounds
    self.addSubview(view)
}

}
  1. And Added on UIView in MainViewController and link to TestView with custom class name.

  2. After that i run the app, I can see the UI from testView. Image of emulator and result

  3. But my custom UI don't show in MainViewController in xcode Image of xcode view controller

How can i enable to see my custom UI in MainViewController ? Thanks


Solution

  • I just changed the setup function. It working now. Final Result Image - It showing UI in IB

    func setup() {
        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))
    
        self.addSubview(view)
    }
    
    func loadViewFromNib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: "TestView", bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
        return view
    }