Skip to content

Instantly share code, notes, and snippets.

@efremidze
Created October 3, 2017 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save efremidze/284787ca86ec68a8be56764cca07481e to your computer and use it in GitHub Desktop.
Save efremidze/284787ca86ec68a8be56764cca07481e to your computer and use it in GitHub Desktop.
public class ContainerView<V: UIView>: UIView {
private var topConstraint: NSLayoutConstraint!
private var bottomConstraint: NSLayoutConstraint!
private var leftConstraint: NSLayoutConstraint!
private var rightConstraint: NSLayoutConstraint!
/// The view inside the container.
public let contentView: V
/**
* Wraps a view inside a container.
* - parameter view: The subview to use as the content view
*/
public init(_ view: V) {
self.contentInset = .zero
self.contentView = view
super.init(frame: .zero)
addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
topConstraint = contentView.topAnchor.constraint(equalTo: topAnchor)
bottomConstraint = contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
leftConstraint = contentView.leftAnchor.constraint(equalTo: leftAnchor)
rightConstraint = contentView.rightAnchor.constraint(equalTo: rightAnchor)
NSLayoutConstraint.activate([topConstraint, bottomConstraint, leftConstraint, rightConstraint])
}
public required init?(coder aDecoder: NSCoder) {
fatalError("InsetView must be initialized with a view using the init(_:) initalizer.")
}
// MARK: - Insets
/// The spacing between the edges of the container and those of the content view.
public var contentInset: UIEdgeInsets {
didSet {
updateInsets()
}
}
private func updateInsets() {
topConstraint.constant = contentInset.top
bottomConstraint.constant = -(contentInset.bottom)
leftConstraint.constant = contentInset.left
rightConstraint.constant = -(contentInset.right)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment