I am generating View and setting constraints programmatically in UIViewController
import UIKit
import SnapKit
class LoginViewController: UIViewController {
lazy var topImageView = UIImageView()
lazy var centerStackView = UIStackView()
lazy var phoneTextField = UITextField()
lazy var sendOTPButton = UIButton()
lazy var bottomStackView = UIStackView()
lazy var separatorLine = UILabel()
lazy var signUpButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
makeUI()
}
private func makeUI() {
self.view.backgroundColor = .white
self.view.addSubview(topImageView)
topImageView.backgroundColor = UIColor.magenta.withAlphaComponent(0.4)
topImageView.snp.makeConstraints {(make) -> Void in
make.width.equalToSuperview()
make.height.equalTo(225)
make.topMargin.equalToSuperview()
make.centerX.equalToSuperview()
}
centerStackView.translatesAutoresizingMaskIntoConstraints = false
centerStackView.axis = .vertical
centerStackView.distribution = .fillEqually
self.view.addSubview(phoneTextField)
self.view.addSubview(sendOTPButton)
self.view.addSubview(centerStackView)
centerStackView.addArrangedSubview(phoneTextField)
centerStackView.addArrangedSubview(sendOTPButton)
phoneTextField.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
phoneTextField.delegate = self
sendOTPButton.setTitle("Send OTP", for: .normal)
sendOTPButton.addTarget(self, action: #selector(generateAccessToken), for: .touchUpInside)
sendOTPButton.backgroundColor = .blue
centerStackView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.width.equalToSuperview()
make.height.equalTo(100)
}
bottomStackView.translatesAutoresizingMaskIntoConstraints = false
bottomStackView.axis = .vertical
bottomStackView.distribution = .fillProportionally
self.view.addSubview(separatorLine)
self.view.addSubview(signUpButton)
self.view.addSubview(bottomStackView)
bottomStackView.addArrangedSubview(separatorLine)
bottomStackView.addArrangedSubview(signUpButton)
separatorLine.backgroundColor = .white
signUpButton.backgroundColor = .orange
bottomStackView.snp.makeConstraints { (make) in
make.bottomMargin.equalTo(additionalSafeAreaInsets)
make.width.equalToSuperview()
make.height.equalTo(80)
}
}
The makeUI
functions essentially creates the views, adds them to UIController
's view (as a subview) and set constraints on them (AutoLayout).
But the ViewController become bulky if more UIView
s are added.
My question is:
- Should I move the UI code to another file (say
LoginView.swift
)? Or is it recommended to keep the UI code inUIViewController
as they are tightly coupled?