Skip to content

Instantly share code, notes, and snippets.

@irace
Last active November 29, 2017 19:31
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irace/3284879705eabe1126cf to your computer and use it in GitHub Desktop.
Save irace/3284879705eabe1126cf to your computer and use it in GitHub Desktop.
I’m building a complex new app entirely with programmatic Auto Layout. It only supports iOS 9 so that means `UIStackView` and `NSLayoutAnchor` exclusively. These two classes have been very handy thus far, in the spirit of composition over inheritance.
final class CenteringView: UIView {
// MARK: - Initialization
init(contentView: UIView) {
super.init(frame: .zero)
addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activateConstraints([
centerXAnchor.constraintEqualToAnchor(contentView.centerXAnchor),
centerYAnchor.constraintEqualToAnchor(contentView.centerYAnchor),
widthAnchor.constraintGreaterThanOrEqualToAnchor(contentView.widthAnchor),
heightAnchor.constraintGreaterThanOrEqualToAnchor(contentView.heightAnchor)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public final class MarginView: UIView {
private let margins: UIEdgeInsets
// MARK: - Initialization
public convenience init(layoutMargin: CGFloat, contentView: UIView) {
self.init(layoutMargins: UIEdgeInsets(top: layoutMargin, left: layoutMargin, bottom: layoutMargin,
right: layoutMargin), contentView: contentView)
}
public init(layoutMargins: UIEdgeInsets, contentView: UIView) {
margins = layoutMargins
super.init(frame: .zero)
addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activateConstraints([
contentView.topAnchor.constraintEqualToAnchor(layoutMarginsGuide.topAnchor),
contentView.leadingAnchor.constraintEqualToAnchor(layoutMarginsGuide.leadingAnchor),
contentView.trailingAnchor.constraintEqualToAnchor(layoutMarginsGuide.trailingAnchor),
contentView.bottomAnchor.constraintEqualToAnchor(layoutMarginsGuide.bottomAnchor)
])
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - UIView
public override func didMoveToSuperview() {
super.didMoveToSuperview()
// http://stackoverflow.com/a/34146177
layoutMargins = margins
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment