Skip to content

Instantly share code, notes, and snippets.

@calvingit
Created November 4, 2023 11:44
Show Gist options
  • Save calvingit/fabbf41fd54798bdc89bce959ac030f7 to your computer and use it in GitHub Desktop.
Save calvingit/fabbf41fd54798bdc89bce959ac030f7 to your computer and use it in GitHub Desktop.
import UIKit
extension UIView {
/// UIView 添加 Auto Layout
@objc func layout(_ constraints: [NSLayoutConstraint]) {
translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(constraints)
}
/// 简单的边缘对齐superView
@objc func pinEdgesToSuperview() {
guard let superview = superview else {
fatalError("请先添加到superview")
}
layout([
leftAnchor.constraint(equalTo: superview.leftAnchor),
rightAnchor.constraint(equalTo: superview.rightAnchor),
topAnchor.constraint(equalTo: superview.topAnchor),
bottomAnchor.constraint(equalTo: superview.bottomAnchor),
])
}
}
extension NSLayoutConstraint {
@objc func offset(_ constant: CGFloat) -> NSLayoutConstraint {
self.constant = constant
return self
}
func priority(_ p: UILayoutPriority) -> NSLayoutConstraint {
self.priority = p
return self
}
}
/// 用于 top bottom leading trailing
extension NSLayoutAnchor {
@objc func equalTo(_ anchor: NSLayoutAnchor) -> NSLayoutConstraint {
constraint(equalTo: anchor)
}
@objc func greaterThanOrEqualTo(_ anchor: NSLayoutAnchor) -> NSLayoutConstraint {
constraint(greaterThanOrEqualTo: anchor)
}
@objc func lessThanOrEqualTo(_ anchor: NSLayoutAnchor) -> NSLayoutConstraint {
constraint(lessThanOrEqualTo: anchor)
}
}
/// 用于 width 和 height
extension NSLayoutDimension {
@objc func equal(_ constant: CGFloat) -> NSLayoutConstraint {
constraint(equalToConstant: constant)
}
@objc func greaterThanOrEqual(_ constant: CGFloat) -> NSLayoutConstraint {
constraint(greaterThanOrEqualToConstant: constant)
}
@objc func lessThanOrEqual(_ constant: CGFloat) -> NSLayoutConstraint {
constraint(lessThanOrEqualToConstant: constant)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment