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

1 Answer 1

0
\$\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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.