How to simplify anchor with NSLayoutConstraint in iOS

Issue #368

See https://github.com/onmyway133/Omnia/blob/master/Sources/iOS/NSLayoutConstraint.swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
extension NSLayoutConstraint {

/// Disable auto resizing mask and activate constraints
///
/// - Parameter constraints: constraints to activate
static func on(_ constraints: [NSLayoutConstraint]) {
constraints.forEach {
($0.firstItem as? UIView)?.translatesAutoresizingMaskIntoConstraints = false
$0.isActive = true
}
}

static func on(_ constraintsArray: [[NSLayoutConstraint]]) {
let constraints = constraintsArray.flatMap({ $0 })
NSLayoutConstraint.on(constraints)
}

func priority(_ value: Float) -> NSLayoutConstraint {
priority = UILayoutPriority(value)
return self
}
}

extension Array where Element == NSLayoutConstraint {
func priority(_ value: Float) -> [NSLayoutConstraint] {
forEach {
$0.priority = UILayoutPriority(value)
}

return self
}
}
1
2
3
4
5
6
7
8
9
10
extension UILayoutGuide {
func pinEdges(view: UIView, inset: UIEdgeInsets = UIEdgeInsets.zero) -> [NSLayoutConstraint] {
return [
leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: inset.left),
trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: inset.right),
topAnchor.constraint(equalTo: view.topAnchor, constant: inset.top),
bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: inset.bottom)
]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
extension UIView {
func pinEdges(view: UIView, inset: UIEdgeInsets = UIEdgeInsets.zero) -> [NSLayoutConstraint] {
return [
leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: inset.left),
trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: inset.right),
topAnchor.constraint(equalTo: view.topAnchor, constant: inset.top),
bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: inset.bottom)
]
}

func pinCenter(view: UIView, offset: CGPoint = .zero) -> [NSLayoutConstraint] {
return [
centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: offset.x),
centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: offset.y)
]
}

func padding(view: UIView, _ constant: CGFloat = 0) -> [NSLayoutConstraint] {
return [
leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: constant),
trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -constant)
]
}

func size(_ constant: CGFloat) -> [NSLayoutConstraint] {
return [
widthAnchor.constraint(equalToConstant: constant),
heightAnchor.constraint(equalToConstant: constant)
]
}

func size(_ width: CGFloat, _ height: CGFloat) -> [NSLayoutConstraint] {
return [
widthAnchor.constraint(equalToConstant: width),
heightAnchor.constraint(equalToConstant: height)
]
}

func addSubviews(_ views: [UIView]) {
views.forEach {
addSubview($0)
}
}
}

Comments