Skip to content

Instantly share code, notes, and snippets.

@thomsmed
Created September 11, 2021 15:32
Show Gist options
  • Save thomsmed/09acddd9f91be176628c901e2c64512e to your computer and use it in GitHub Desktop.
Save thomsmed/09acddd9f91be176628c901e2c64512e to your computer and use it in GitHub Desktop.
Rounded UIView with shadow and border
//
// RoundedView.swift
//
@IBDesignable
class RoundedView: UIView {
private let borderView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
@IBInspectable var cornerRadius: Int = 0 {
didSet {
layer.cornerRadius = CGFloat(cornerRadius)
borderView.layer.cornerRadius = CGFloat(cornerRadius)
borderView.layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable var borderWidth: Int = 0 {
didSet {
borderView.layer.borderWidth = CGFloat(borderWidth)
}
}
@IBInspectable var borderColor: UIColor = .clear {
didSet {
borderView.layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var shadowColor: UIColor = .black {
didSet {
layer.shadowColor = shadowColor.cgColor
}
}
@IBInspectable var shadowRadius: Int = 0 {
didSet {
layer.shadowRadius = CGFloat(shadowRadius)
}
}
@IBInspectable var shadowOpacity: Float = 0 {
didSet {
layer.shadowOpacity = shadowOpacity
}
}
@IBInspectable var shadowOffset: CGSize = CGSize(width: 0, height: 0) {
didSet {
layer.shadowOffset = shadowOffset
}
}
override func layoutSubviews() {
super.layoutSubviews()
layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
private func configure() {
translatesAutoresizingMaskIntoConstraints = false
addSubview(borderView)
NSLayoutConstraint.activate([
borderView.topAnchor.constraint(equalTo: topAnchor),
borderView.bottomAnchor.constraint(equalTo: bottomAnchor),
borderView.leftAnchor.constraint(equalTo: leftAnchor),
borderView.rightAnchor.constraint(equalTo: rightAnchor),
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment