Skip to content

Instantly share code, notes, and snippets.

@srstanic
Last active November 9, 2022 10:50
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 srstanic/42020ce6c02e49988e3d4af320952045 to your computer and use it in GitHub Desktop.
Save srstanic/42020ce6c02e49988e3d4af320952045 to your computer and use it in GitHub Desktop.
extension UIView {
static func withoutConstraints() -> Self {
let instance = self.init()
instance.translatesAutoresizingMaskIntoConstraints = false
return instance
}
func addSubviews(_ views: UIView...) {
for view in views {
addSubview(view)
}
}
}
protocol CodedView {
func setupViews()
func setupLayout()
}
extension CodedView where Self: UIView {
func setup() {
setupViews()
setupLayout()
}
}
// convenience 'abstract' class to reduce boilerplate in custom view classes
// similar can be done for UITableView, UICollectionView, etc
class CodedUIView: UIView, CodedView {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not supported")
}
func setupViews() {}
func setupLayout() {}
}
class SomeView: CodedUIView {
private let labelView = UILabel.withoutConstraints()
private let imageView = UIImageView.withoutConstraints()
override func setupViews() {
addSubviews(labelView, imageView)
setupLabel()
setupImage()
}
private func setupLabel() {
labelView.text = "Some text"
// ...
}
private func setupImage() {
imageView.image = UIImage()
// ...
}
override func setupLayout() {
labelView.trailingAnchor.constraint(equalTo: imageView.leadingAnchor, constant: 10).isActive = true
//...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment