Skip to content

Instantly share code, notes, and snippets.

@wata
Created May 31, 2023 06:48
Show Gist options
  • Save wata/abc80bed53440ee2d524c547574995ba to your computer and use it in GitHub Desktop.
Save wata/abc80bed53440ee2d524c547574995ba to your computer and use it in GitHub Desktop.
Swift Extension for adding borders to any side of UIView
extension UIView {
struct Side: OptionSet {
let rawValue: Int
static let left = Side(rawValue: 1 << 0)
static let right = Side(rawValue: 1 << 1)
static let top = Side(rawValue: 1 << 2)
static let bottom = Side(rawValue: 1 << 3)
}
func addBorders(color: UIColor, width: CGFloat, to side: Side, for size: CGSize) {
if side.contains(.left) {
addBorder(color: color, frame: .init(x: 0, y: 0, width: width, height: size.height))
}
if side.contains(.right) {
addBorder(color: color, frame: .init(x: size.width - width, y: 0, width: width, height: size.height))
}
if side.contains(.top) {
addBorder(color: color, frame: .init(x: 0, y: 0, width: size.width, height: width))
}
if side.contains(.bottom) {
addBorder(color: color, frame: .init(x: 0, y: size.height - width, width: size.width, height: width))
}
}
private func addBorder(color: UIColor, frame: CGRect) {
let border = CALayer()
border.frame = frame
border.backgroundColor = color.cgColor
layer.addSublayer(border)
}
func removeBorders() {
layer.sublayers?.forEach {
guard $0 is BorderLayer else { return }
$0.removeFromSuperlayer()
}
}
}
private class BorderLayer: CALayer {}
@wata
Copy link
Author

wata commented May 31, 2023

Usage

if isBorderEnabled {
    addBorders(color: .red, width: 1, to: [.top, .bottom], for: bounds.size)
} else {
    removeBorders()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment