Last active
November 7, 2017 10:09
-
-
Save ksmandersen/3002042a47c6bc38d4d8d9837ea0308e to your computer and use it in GitHub Desktop.
Layout Anchor Helpers
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 Foundation | |
import UIKit | |
extension UIView { | |
func addSubviews(_ subviews: [UIView]) { | |
for view in subviews { | |
addSubview(view) | |
} | |
} | |
} | |
extension UIView { | |
@discardableResult | |
func anchorToCenter(of view: UIView, offset: CGPoint = .zero) -> [NSLayoutConstraint] { | |
return view.apply(constraints: [ | |
centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: offset.x), | |
centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: offset.y), | |
]) | |
} | |
@discardableResult | |
func anchorToCenterOfSuperview(offset: CGPoint = .zero) -> [NSLayoutConstraint] { | |
return anchorToCenter(of: superview!, offset: offset) | |
} | |
@discardableResult | |
func anchorToEdges(of view: UIView, insets: UIEdgeInsets = .zero) -> [NSLayoutConstraint] { | |
return view.apply(constraints: [ | |
topAnchor.constraint(equalTo: view.topAnchor, constant: insets.top), | |
bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -insets.bottom), | |
leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: insets.left), | |
trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -insets.right), | |
]) | |
} | |
@discardableResult | |
func anchorToEdgesOfSuperview(insets: UIEdgeInsets = .zero) -> [NSLayoutConstraint] { | |
return anchorToEdges(of: superview!, insets: insets) | |
} | |
@discardableResult | |
func apply(constraints: [NSLayoutConstraint]) -> [NSLayoutConstraint] { | |
constraints.forEach({ self.apply(constraint: $0) }) | |
return constraints | |
} | |
@discardableResult | |
func apply(constraint: NSLayoutConstraint) -> NSLayoutConstraint { | |
(constraint.firstItem as? UIView)?.translatesAutoresizingMaskIntoConstraints = false | |
constraint.isActive = true | |
return constraint | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment