3
\$\begingroup\$

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
 }
}
asked Jun 27, 2017 at 3:44
\$\endgroup\$
1
  • \$\begingroup\$ I suppose the approach is acceptable? \$\endgroup\$ Commented Jun 28, 2017 at 3:09

1 Answer 1

1
\$\begingroup\$

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
answered Jul 12, 2017 at 8:03
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.