@IBDesignable and @IBInspectable in Swift 3 .

IBDesignable and IBInspectable , a way to create custom elements and the attributes . This can be directly added to the iOS Interface Builder.

This WWDC 2015 video explains how to implement custom UI elements.

IBDesignable

IBDesignable attribute will identify the UIView or the elements inherited from UIView — Eg: UIButton, UIImageView, UILabel etc..

For example , I created a Custom UIButton class,

@IBDesignable
open class KGHighLightedButton: UIButton {
public override init(frame: CGRect) {
super.init(frame: frame)
setTitle("MyTitle", for: .normal)
setTitleColor(UIColor.blue, for: .normal)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}

After adding this class, in your ViewController import the custom class

#import KGHighLightedButton

In the Interface Builder (`StoryBoard`) drag and drop a UIButton. Go to the `Show the Identity Inspector` and set the Class and Module as `KGHighLightedButton`.

IBInspectable

Lets add some custom properties our button. 🙌 🙌

For this we have to use IBInspectable attribute. Let’s see how we can add them.

@IBInspectable
public var cornerRadius: CGFloat = 2.0 {
didSet {
self.layer.cornerRadius = self.cornerRadius
}
}

This will add the corner_radius property to your button. You will be able to see them in the Attributes Inspector .

IBInspectable can be used with the below types,

  • Int
  • CGFloat
  • Double
  • String
  • Bool
  • CGPoint
  • CGSize
  • CGRect
  • UIColor
  • UIImage

You can see my projects here https://github.com/Gypsyan .