Skip to content

Instantly share code, notes, and snippets.

@agustr
Created December 1, 2020 18:35
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 agustr/3c37fcc20a655e67a60eca3f04e25933 to your computer and use it in GitHub Desktop.
Save agustr/3c37fcc20a655e67a60eca3f04e25933 to your computer and use it in GitHub Desktop.
boilerplate code for view controllers root view
// boilerplate for uiview subclass that is intended to be used as uiviewcontrollers
// root view using constraints.
class CustomView: UIView {
// custom views should override this to return true if
// they cannot layout correctly using autoresizing.
// from apple docs https://developer.apple.com/documentation/uikit/uiview/1622549-requiresconstraintbasedlayout
override class var requiresConstraintBasedLayout: Bool {
return true
}
lazy var subView: UIView = {
// Snazy way of instantiating subviews
let subView = UIView()
subView.backgroundColor = .green
subView.translatesAutoresizingMaskIntoConstraints = false
return subView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
// Configure self
backgroundColor = .white
// Add subviews
addSubview(subView)
// Configure layout
setupLayout()
// setup internal actions for the view
setupActions()
}
private func setupActions() {
// setup the internal actions for the view.
// addButton.addTarget(self, action: #selector(moveHeaderView), for: .touchUpInside)
}
private func setupLayout() {
NSLayoutConstraint.activate([
subView.topAnchor.constraint(equalTo: topAnchor),
subView.leadingAnchor.constraint(equalTo: leadingAnchor),
subView.trailingAnchor.constraint(equalTo: trailingAnchor),
subView.heightAnchor.constraint(equalToConstant: 40)
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment