Last active
December 8, 2022 12:53
-
-
Save AlexChekel1337/ccdc39610877644e7b34a885c3efb951 to your computer and use it in GitHub Desktop.
Labels edges of a given view
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 LabeledEdge: OptionSet { | |
let rawValue: Int | |
static let leading = Self(rawValue: 1 << 0) | |
static let top = Self(rawValue: 1 << 1) | |
static let trailing = Self(rawValue: 1 << 2) | |
static let bottom = Self(rawValue: 1 << 3) | |
static let all: Self = [.leading, .top, .trailing, .bottom] | |
} | |
@discardableResult | |
func labelEdges(_ edges: LabeledEdge, with text: String) -> [UILabel] { | |
let setupLabel: (String) -> UILabel = { text in | |
let label = UILabel() | |
label.alpha = 0.5 | |
label.font = UIFont.systemFont(ofSize: 10) | |
label.textColor = .label | |
label.text = text | |
label.translatesAutoresizingMaskIntoConstraints = false | |
return label | |
} | |
var labelsToReturn: [UILabel] = [] | |
if edges.contains(.leading) { | |
let label = setupLabel("\(text) (leading)") | |
label.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2) | |
addSubview(label) | |
label.centerXAnchor.constraint(equalTo: leadingAnchor, constant: label.font.lineHeight / 2).isActive = true | |
label.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true | |
labelsToReturn.append(label) | |
} | |
if edges.contains(.top) { | |
let label = setupLabel("\(text) (top)") | |
addSubview(label) | |
label.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true | |
label.centerYAnchor.constraint(equalTo: topAnchor, constant: label.font.lineHeight / 2).isActive = true | |
labelsToReturn.append(label) | |
} | |
if edges.contains(.trailing) { | |
let label = setupLabel("\(text) (trailing)") | |
label.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2) | |
addSubview(label) | |
label.centerXAnchor.constraint(equalTo: trailingAnchor, constant: -label.font.lineHeight / 2).isActive = true | |
label.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true | |
labelsToReturn.append(label) | |
} | |
if edges.contains(.bottom) { | |
let label = setupLabel("\(text) (bottom)") | |
addSubview(label) | |
label.centerYAnchor.constraint(equalTo: bottomAnchor, constant: -label.font.lineHeight / 2).isActive = true | |
label.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true | |
labelsToReturn.append(label) | |
} | |
return labelsToReturn | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are some examples of how it can be used:
.all
[.leading, .top]