IBDesignable and IBInspectable in Swift

Make Custom view by @IBDesignable with Effects and Animation

Anand Nimje
2 min readMar 2, 2018

Its helps for making custom layout directly in Interface Builder. Easy to create any custom view and direly you can provide there any effects like border width, border color, corner radius, shadow color, shadow width, shadow Opacity.

Here i will show you how to create custom view with the help of @IBDesignable

You just need to download ANCustom view file from Github repo then drag and drop into your project.

After that you need to go your UIView’s Identity inspector and add custom class as a ANCustomView.

Add custom class in Xcode StoryBoard

There you will be able to see all options which i have mention above -

Inside Xcode StoryBoard Interface builder

Code below which i have used inside Custom UIView Class -

@IBInspectable var cornerRadius: Double {
get {
return Double(self.layer.cornerRadius)
}set {
self.layer.cornerRadius = CGFloat(newValue)
}
}
@IBInspectable var borderWidth: Double {
get {
return Double(self.layer.borderWidth)
}
set {
self.layer.borderWidth = CGFloat(newValue)
}
}
@IBInspectable var borderColor: UIColor? {
get {
return UIColor(cgColor: self.layer.borderColor!)
}
set {
self.layer.borderColor = newValue?.cgColor
}
}
@IBInspectable var shadowColor: UIColor? {
get {
return UIColor(cgColor: self.layer.shadowColor!)
}
set {
self.layer.shadowColor = newValue?.cgColor
}
}
@IBInspectable var shadowOpacity: Float {
get {
return self.layer.shadowOpacity
}
set {
self.layer.shadowOpacity = newValue
}
}

Based on your requirements you can adjust attribute value.

Also we can add code for animation Effects for our View inside custom class -

private func provideAnimation(animationDuration:TimeInterval, deleyTime:TimeInterval, springDamping:CGFloat, springVelocity:CGFloat){
self.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
UIView.animate(withDuration: animationDuration,
delay: deleyTime,
usingSpringWithDamping: springDamping,
initialSpringVelocity: springVelocity,
options: .allowUserInteraction,
animations: {
self.transform = CGAffineTransform.identity
})
}

You can find full project from here.

Finally we know now how to create with in less code efforts good UIViews for our iOS app from direct Interface builder. Lets check video -

Thank You !

I hope you will like this. 😊 Thanks for reading. 🎉

If you having any query regarding this tutorial ? or want to know something more about it. Twitter me: @Anand

--

--