Interface Builder can make laying out complex UI a breeze. It saves a lot of time and is becoming even better and more powerful with every Xcode update. However, it is not that perfect (yet) and trivial tasks like rounding a view’s corners in IB may require doing something like this:
Yikes! Defining runtime attributes in IB is error-prone and kinda time consuming.
There is a better way of accessing the properties your view’s underlying CALayer
in IB. All you have to do is to create an extension for UIView
 class with properties that proxy its layer’s properties and apply @IBInspectable
attribute to each of those properties:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
extension UIView { @IBInspectable var cornerRadius: CGFloat { get { return self.layer.cornerRadius } set { self.layer.cornerRadius = newValue } } @IBInspectable var borderWidth: CGFloat { get { return self.layer.borderWidth } set { self.layer.borderWidth = newValue } } @IBInspectable var borderColor: UIColor? { get { guard let layerBorderColor = self.layer.borderColor else { return nil } return UIColor(cgColor: layerBorderColor) } set { self.layer.borderColor = newValue?.cgColor } } } |
With this extension in place, you will notice that any view in IB will have a new set of attributes in Attribute inspector:
Ah, much better, isn’t it?
I hope this will make your experience with Interface Builder even more enjoyable. Happy coding! 🙂