In an effort to reduce the size of a View Controller class I am wondering if this structure is an acceptable, safe way to modify the UI on a Controller Class.
The only thing that I see "wrong" with this approach is not being able to set my outlets or variables to private which is usually very import in order to minimize cohesion and keep the files conforming to Single Responsibility Principle
// In File ViewController.swift
final class ViewController: UIViewController {
@IBOutlet weak var myButton: UIButton
@IBOutlet weak var mylabel : UILabel
@IBOutlet weak var myview : UIView
private lazy var viewModel: VCViewModel = {
return VCViewModel(main: self)
}()
override func viewDidLoad() {
super.viewDidLoad()
initializeUI()
}
func initializeUI() {
viewModel.configureMyButton()
viewModel.configureMyLabel()
viewModel.configureMyView()
}
...
}
// Seperate File VCViewModel.swift
final class VCViewModel {
private main: UIViewController
init(main: UIViewController) {
self.main = main
}
func configureMyButton() {
main.myButton.titleLabel.title = "This class configures all UI related code"
}
func configureMyLabel() {
main.myLabel.backgroundColor = UIColor.green
}
func configureMyView() {
main.myLabel.isHidden = true
}
}
-
\$\begingroup\$ I suppose the approach is acceptable? \$\endgroup\$lifewithelliott– lifewithelliott2017年06月28日 03:09:50 +00:00Commented Jun 28, 2017 at 3:09
1 Answer 1
You should read more up on MVVM, It would be better for your ViewModel to have no UIKit Dependencies. Testing your implementation will be difficult too.
Ideally, public properties on your ViewModel i.e titleText
and color
and in your VC;
self.titleLabel.text = viewModel.titleText
self.titleLabel.backGroundColor = viewModel.titleBackgroundColor