Last active
November 11, 2023 10:35
-
-
Save diegoventura/a96d7d8c5c5cdcef15e9c0fb9956e5a6 to your computer and use it in GitHub Desktop.
Extension to add borders to a UIView with Auto Layout
This file contains 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
public extension UIView { | |
func addBorder(to edges: UIRectEdge, color: UIColor = UIColor.white, thickness: CGFloat = 1) { | |
var borders = [UIView]() | |
func border() -> UIView { | |
let border = UIView(frame: CGRect.zero) | |
border.backgroundColor = color | |
border.translatesAutoresizingMaskIntoConstraints = false | |
return border | |
} | |
if edges.contains(.top) || edges.contains(.all) { | |
let top = border() | |
addSubview(top) | |
addConstraints( | |
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[top(==thickness)]", | |
options: [], | |
metrics: ["thickness": thickness], | |
views: ["top": top])) | |
addConstraints( | |
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[top]-(0)-|", | |
options: [], | |
metrics: nil, | |
views: ["top": top])) | |
borders.append(top) | |
} | |
if edges.contains(.left) || edges.contains(.all) { | |
let left = border() | |
addSubview(left) | |
addConstraints( | |
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[left(==thickness)]", | |
options: [], | |
metrics: ["thickness": thickness], | |
views: ["left": left])) | |
addConstraints( | |
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[left]-(0)-|", | |
options: [], | |
metrics: nil, | |
views: ["left": left])) | |
borders.append(left) | |
} | |
if edges.contains(.right) || edges.contains(.all) { | |
let right = border() | |
addSubview(right) | |
addConstraints( | |
NSLayoutConstraint.constraints(withVisualFormat: "H:[right(==thickness)]-(0)-|", | |
options: [], | |
metrics: ["thickness": thickness], | |
views: ["right": right])) | |
addConstraints( | |
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[right]-(0)-|", | |
options: [], | |
metrics: nil, | |
views: ["right": right])) | |
borders.append(right) | |
} | |
if edges.contains(.bottom) || edges.contains(.all) { | |
let bottom = border() | |
addSubview(bottom) | |
addConstraints( | |
NSLayoutConstraint.constraints(withVisualFormat: "V:[bottom(==thickness)]-(0)-|", | |
options: [], | |
metrics: ["thickness": thickness], | |
views: ["bottom": bottom])) | |
addConstraints( | |
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[bottom]-(0)-|", | |
options: [], | |
metrics: nil, | |
views: ["bottom": bottom])) | |
borders.append(bottom) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment