Created
May 31, 2023 06:48
-
-
Save wata/abc80bed53440ee2d524c547574995ba to your computer and use it in GitHub Desktop.
Swift Extension for adding borders to any side of UIView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage