Round buttons with shadow

Jeroen de Vrind
Short Swift Stories
2 min readJul 11, 2019
Photo by Graphic Node on Unsplash

Almost in every project I need a view or a button that has rounded corners and sometimes even a bit of shadow at the same time. It can be a bit hard when you start to apply both to the same view.

This is a base class you can use to create a round button with or without shadow. You can make something similar for views:

@IBDesignable class RoundButton: UIButton {   // MARK: - Properties   @IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
setNeedsLayout()
}
}
@IBInspectable var shadowColor: UIColor = UIColor.darkGray {
didSet {
setNeedsLayout()
}
}
@IBInspectable var shadowOffsetWidth: CGFloat = 0.0 {
didSet {
setNeedsLayout()
}
}
@IBInspectable var shadowOffsetHeight: CGFloat = 1.8 {
didSet {
setNeedsLayout()
}
}
@IBInspectable var shadowOpacity: Float = 0.30 {
didSet {
setNeedsLayout()
}
}
@IBInspectable var shadowRadius: CGFloat = 3.0 {
didSet {
setNeedsLayout()
}
}
private var shadowLayer: CAShapeLayer = CAShapeLayer() {
didSet {
setNeedsLayout()
}
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = cornerRadius
shadowLayer.path = UIBezierPath(roundedRect: bounds,
cornerRadius: cornerRadius).cgPath
shadowLayer.fillColor = backgroundColor?.cgColor
shadowLayer.shadowColor = shadowColor.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: shadowOffsetWidth,
height: shadowOffsetHeight)
shadowLayer.shadowOpacity = shadowOpacity
shadowLayer.shadowRadius = shadowRadius
layer.insertSublayer(shadowLayer, at: 0)
}
}

Thanks to IBDesignable you’ll also have a nice preview in your Xib-file or Storyboard. And thanks to IBInspectable you can change the properties right in your xib/storyboard.

Btw…is your app already accessible? Legislation is coming up in Europe and your app should meet the Web Content Accessibility Guidelines. You can read all about accessibility in my book: ‘How to develop accessible iOS apps’ available in the Apple Book Store.

--

--

Jeroen de Vrind
Short Swift Stories

iOS Engineer at ABN Amro bank. Author of How to develop accessible iOS apps.