Skip to content

Instantly share code, notes, and snippets.

@jonahb
Created February 7, 2019 04:37
Show Gist options
  • Save jonahb/e69ce706efaddf8080dccf76645ce3ff to your computer and use it in GitHub Desktop.
Save jonahb/e69ce706efaddf8080dccf76645ce3ff to your computer and use it in GitHub Desktop.
//
// AdaptiveLabel.swift
// Coop
//
// Created by Jonah Burke on 1/17/19.
// Copyright © 2019 Jonah Burke. All rights reserved.
//
import UIKit
class AdaptiveLabel: UIView, UIContentSizeCategoryAdjusting {
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
isAccessibilityElement = true
accessibilityTraits = .staticText
label.adjustsFontForContentSizeCategory = false
label.translatesAutoresizingMaskIntoConstraints = false
addSubview(label)
label.align(to: self)
update()
}
var adjustsFontForContentSizeCategory: Bool = true
private let label = UILabel()
var textOptions: [String] = ["Label"] {
didSet {
update()
}
}
var textStyle: UIFont.TextStyle = UIFont.TextStyle.body {
didSet {
update()
}
}
var textAlignment: NSTextAlignment {
get {
return label.textAlignment
}
set {
label.textAlignment = newValue
}
}
var textColor: UIColor {
get {
return label.textColor
}
set {
label.textColor = newValue
}
}
private var font: UIFont {
return UIFont.preferredFont(forTextStyle: textStyle)
}
override var intrinsicContentSize: CGSize {
return label.intrinsicContentSize
}
override func layoutSubviews() {
super.layoutSubviews()
update()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if adjustsFontForContentSizeCategory && traitCollection.preferredContentSizeCategory != previousTraitCollection?.preferredContentSizeCategory {
update()
}
}
private func update() {
label.font = font
let attributes = [NSAttributedString.Key.font: font]
let text = textOptions.first {
NSString(string: $0).size(withAttributes: attributes).width < label.bounds.width
}
label.text = text ?? textOptions.last
accessibilityLabel = text
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment