Creating custom user interface files with XIB in Xcode 6 and Swift

In this video I am showing you how to create custom user interface file with XIB in Xcode 6 and how to load it as a Subview programatically as well as using Main.storyboard.

Source code of MyCustomView file:

import UIKit

@IBDesignable
class MyCustomView: UIView {

@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var myImage: UIImageView!
@IBOutlet weak var myButton: UIButton!

var view:UIView!

@IBInspectable
var mytitleLabelText: String? {
get {
return titleLabel.text
}
set(mytitleLabelText) {
titleLabel.text = mytitleLabelText
}
}

@IBInspectable
var myCustomImage:UIImage? {
get {
return myImage.image
}
set(myCustomImage) {
myImage.image = myCustomImage
}
}

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

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

func setup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeightaddSubview(view)
}

func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass:self.dynamicType)
let nib = UINib(nibName: “MyCustomView”, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as UIView

return view
}
}

  • Twilight Sparkle

    Thank you for great screencast! It would be even more helpful if you paste code snippets via github (with indentation and colors).

    • I formatted source code a little bit. If you still need it.

      • Dipankar Das

        Could you please upload your project?

  • Adam Farah

    I wonder if Paul Solt knows you’ve directly ripped off his screencast @paulsolt

  • Dipankar Das

    i am getting

    Main.storyboard: error: IB Designables: Failed to update auto layout status: The agent raised a “NSInternalInconsistencyException” exception: Could not load NIB in bundle: ‘NSBundle (loaded)’ with name ‘anotherView’

    Could you please upload your project?

  • Rajesh sharma

    it good but i want to implement collection view inside xib , how i do ? please help.

  • Alex

    view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] in swift 2.0

  • Alex Alex

    You forgot about addSubview(view) in setup function

  • Lovina

    I am working with swift 2 and used view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]; as view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeightaddSubview(view) was giving me an error. The project did build but then gives an error : Thread1: EXC_BAD_ACCESS(code =2, address = ) on line –> let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView

    Please help!

    • Lovina

      The error screenshot: