Skip to content

Instantly share code, notes, and snippets.

@AlexChekel1337
Last active December 8, 2022 12:53
Show Gist options
  • Save AlexChekel1337/ccdc39610877644e7b34a885c3efb951 to your computer and use it in GitHub Desktop.
Save AlexChekel1337/ccdc39610877644e7b34a885c3efb951 to your computer and use it in GitHub Desktop.
Labels edges of a given view
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
}
}
@AlexChekel1337
Copy link
Author

AlexChekel1337 commented Dec 8, 2022

Here are some examples of how it can be used:

Edges: .all Edges: [.leading, .top]

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