Last active
November 29, 2017 19:31
-
-
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.
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
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") | |
} | |
} |
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
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