Friday, 4 November 2016

Custom UI Elements with IBDesignable

In Xcode 6 two new interface builder declaration attributes were added: IBDesignable and IBInspectable.

IBDesignable updates the view in real time. We prefix out class with @IBDesignable keyword to inform interface builder that the class' instance will try to design  themselves when added to the storyboard:

@IBDesignable class MyCustomView: UIView{

}

Then we prefix any properties of the class with @IBInspectable to ensure that interface builder can read and write the value of these properties directly in the inspector view.

With these two new keyword we can create custom UI controls as per our need and use them directly in interface builder and can change their properties in inspector view as we do with other built in UI controls . To create a custom UI elements we have to perform following steps:

1) Create a View .Xib file and design the required view .

2) Then setup auto layout constraints.

3) Create a .swift file to write code .

4) Set .xib file's  File's Owner custom class to  the class we created in last step .

5) In .swift file implement initializers: init(coder:) and init(frame:) .

6) Load the UIView from  the .xib file using NSBundle and  UINIb classes .

7) Add the  view as a subview and  property  for the class .

8) Add auto resizing masks for the view to match the size of the Custom View itself .

9) Make the  view's frame to have the same size as in design time  by assigning CustomView's bounds .

Here is the sample class code :

import UIKit

@IBDesignable class MyCustomView: UIView {

let nibName = "MyCustomView"
var view: UIView!

@IBInspectable var date: String = "3/19/1990" {
            
             didSet{
                          
                       }
}


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

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

func setupXib() -> Void {

view  =  loadFromNib()
view.frame =  bounds
view.autoresizingMask =  [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
addSubview(view)

}

func loadFromNib() -> UIView {

 let bundle =  NSBundle(forClass: self.dynamicType)

 let nib = UINib(nibName: nibName, bundle: bundle)

 let view =  nib.instantiateWithOwner(self, options:nil)[0] as! UIView

 return view
}

}


Resources:
http://supereasyapps.com/blog/2014/12/15/create-an-ibdesignable-uiview-subclass-with-code-from-an-xib-file-in-xcode-6
https://www.weheartswift.com/make-awesome-ui-components-ios-8-using-swift-xcode-6/

No comments:

Post a Comment