Easily Add Rounded Corners in Interface Builder with @IBInspectable
This guide shows how to set view corner radius directly in Interface Builder using @IBInspectable, covering simple code approaches, runtime attributes, Swift extensions, and Objective‑C categories, with full code examples for both Swift and Objective‑C implementations.
Simple code approach
For programmatic UI you can set the corner radius directly:
view.layer.cornerRadius = 5Storyboard method
Typically developers create an IBOutlet and set the radius in awakeFromNib or viewDidLoad:
@IBOutlet weak var customView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
customView.layer.cornerRadius = 5
}Runtime attributes
Using Interface Builder's Runtime Attributes you can set layer.cornerRadius without code, but key‑path typos and poor readability are common issues.
Best practice with @IBInspectable
Since Xcode 6 you can expose custom properties to Interface Builder with @IBInspectable. Adding an inspectable property to any UIView lets you edit the corner radius directly in the Attributes Inspector. @IBInspectable var customNumber: Int? After adding the property, the inspector shows a field where you can enter the value:
@IBInspectable supports the following types: Boolean Number String Point Size Rect Range Color Image nil
Swift extension implementation
Create a file UIView+O2CornerRadius.swift with the following extension:
import UIKit
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get { return layer.cornerRadius }
set { layer.cornerRadius = newValue }
}
}This lets you set the corner radius for any view directly in Interface Builder, achieving low coupling and high cohesion.
Objective‑C category implementation
For Objective‑C you can add a category with a property backed by the layer’s corner radius:
// UIView+O2CornerRadius.h
@interface UIView (O2CornerRadius)
@property (nonatomic, assign) IBInspectable CGFloat cornerRadius;
@end
// UIView+O2CornerRadius.m
@implementation UIView (O2CornerRadius)
- (void)setCornerRadius:(CGFloat)cornerRadius {
self.layer.cornerRadius = cornerRadius;
}
- (CGFloat)cornerRadius {
return self.layer.cornerRadius;
}
@endBoth Swift and Objective‑C solutions allow you to configure rounded corners without extra code in view controllers.
Aotu Lab
Aotu Lab, founded in October 2015, is a front-end engineering team serving multi-platform products. The articles in this public account are intended to share and discuss technology, reflecting only the personal views of Aotu Lab members and not the official stance of JD.com Technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
