Created
December 1, 2020 18:35
-
-
Save agustr/3c37fcc20a655e67a60eca3f04e25933 to your computer and use it in GitHub Desktop.
boilerplate code for view controllers root view
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
// 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