This is such a common requirement in iOS development, and it was always something that had to be done purely in code (or using images - yuck!). Now it's incredibly easy to preview his kind of thing in Interface Builder, there's absolutely no excuse for not using it.
Here's the code:-
import UIKit
@IBDesignable
class MyRoundedView: UIView {
@IBInspectable var radius: CGFloat = 8 {
didSet {
self.layer.cornerRadius = radius
}
}
override func awakeFromNib() {
self.layer.cornerRadius = self.radius
self.layer.masksToBounds = true
}
}
To use this class, add it to your project and then open the storyboard in IB and create a normal UIView of a decent size. Give it a background colour so you can see it, then navigate to the Identity Inspector in the right-hand Utilities panel and change the class type in the drop-down to MyRoundedView
.
When you do this you should see a third label appear beneath "Class" and "Module" that says "Designables", and it should say "Updating" for a moment before changing to "Up to date". This means that Xcode has recompiled your code for MyRoundedView
successfully.
Now you can open the Attributes Inspector and you should see (maybe after a short pause) a new section at the top of the pane with the heading "My Rounded View" and a new attribute labelled "Radius" with the value 8 (because that is the initial value we set in the code). This has appeared in the Attributes Inspector because we marked it as @IBInspectable
.
You can now change this to another number and you should see the rounded view's corner radius update in real-time!