Skip to content

Instantly share code, notes, and snippets.

@klaaspieter
Created March 7, 2018 09:06
Show Gist options
  • Save klaaspieter/02115e68a32e6586e915c12fb55c2032 to your computer and use it in GitHub Desktop.
Save klaaspieter/02115e68a32e6586e915c12fb55c2032 to your computer and use it in GitHub Desktop.
Convenience UILayoutPriority extension for more declarative content hugging (and compression resistance) definition
import UIKit
import PlaygroundSupport
let view = UIView(frame: CGRect(x: 0, y: 0, width: 414, height: 100))
view.backgroundColor = .white
let titleLabel = UILabel()
titleLabel.text = "Hello"
titleLabel.backgroundColor = .purple
view.addSubview(titleLabel)
let subtitleLabel = UILabel()
subtitleLabel.text = "It's me"
subtitleLabel.backgroundColor = .yellow
view.addSubview(subtitleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
extension UILayoutPriority {
static func + (lhs: UILayoutPriority, rhs: Float) -> UILayoutPriority {
return UILayoutPriority(lhs.rawValue + rhs)
}
static func - (lhs: UILayoutPriority, rhs: Float) -> UILayoutPriority {
return UILayoutPriority(lhs.rawValue - rhs)
}
}
extension UILayoutPriority: Comparable {
public static func < (lhs: UILayoutPriority, rhs: UILayoutPriority) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
extension UIView {
func setContentHuggingPriority(for axis: UILayoutConstraintAxis, lowerThan view: UIView) {
setContentHuggingPriority(for: axis, lowerThan: [view])
}
func setContentHuggingPriority(for axis: UILayoutConstraintAxis, lowerThan views: [UIView]) {
guard let minimumPriority = views.map({ $0.contentHuggingPriority(for: axis) }).min() else {
preconditionFailure()
}
setContentHuggingPriority(minimumPriority - 1, for: axis)
}
}
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraintEqualToSystemSpacingBelow(view.topAnchor, multiplier: 0),
titleLabel.leadingAnchor.constraintEqualToSystemSpacingAfter(view.leadingAnchor, multiplier: 0),
titleLabel.bottomAnchor.constraintEqualToSystemSpacingBelow(view.bottomAnchor, multiplier: 0),
titleLabel.trailingAnchor.constraintEqualToSystemSpacingAfter(
subtitleLabel.leadingAnchor,
multiplier: 0
),
subtitleLabel.topAnchor.constraintEqualToSystemSpacingBelow(view.topAnchor, multiplier: 0),
subtitleLabel.bottomAnchor.constraintEqualToSystemSpacingBelow(view.bottomAnchor, multiplier: 0),
subtitleLabel.trailingAnchor.constraintEqualToSystemSpacingAfter(
view.trailingAnchor,
multiplier: 0
),
])
subtitleLabel.setContentHuggingPriority(for: .horizontal, lowerThan: titleLabel)
PlaygroundPage.current.liveView = view
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment