Convenience UILayoutPriority extension for more declarative content hugging (and compression resistance) definition
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
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