Reputation: 413
I am doing this with out working in MVVM as follows, but what will be the best approach for navigation in MVVM, if possible kindly consider both cases -navigation with or with out data, any clue will be appreciated: Thanks
let st = UIStoryboard.init(name: "Register", bundle: nil)
let register = st.instantiateViewController(withIdentifier: "RegisterVC" ) as! RegisterVC
register.data = self.data
self.navigationController?.pushViewController(register, animated: true)`
Upvotes: 0
Views: 2444
Reputation: 1
extension UIViewController { class func loadNib() -> Self { return loadNib(self) } }
let travelVC = ItenararyConfirmationViewController.loadNib() navigationController?.pushViewController(travelVC, animated: true)
Upvotes: 0
Reputation: 492
This is how I have been navigating between view controllers for sometime now, and have found it to be quite effective. My ViewControllers will generally each have a ViewModel class, which is responsible for logic and/or data loading or saving. I instantiate the view model properties like this in each view controller:
class ExampleViewController: UIViewController {
lazy var viewModel = ExampleViewModel()
override func viewDidLoad() {
super.viewDidLoad()
// Load data to the controller via the view model here
viewModel.loadSomeData()
}
// This could be linked to a button from the UI builder
@IBAction func nextPressed(_ sender: Any) {
// Possibly use the view model to persist data here
viewModel.saveSomeData()
// Then navigate to the next controller
self.navigationController?.pushViewController(NextViewController(), animated: true)
}
}
In the above example, NextViewController would then have its own view model which would handle it's data loading and persistence. How you return the data from the view model to the controller is up to you. If its simple data, you can just return it from the functions, otherwise for more complex or a-synchronous functions you could use a delegate or a closure. Keeping the data out of the controller can stop the class from getting too bloated, and reduces the dependancy of controllers on each other.
So you would generally have some kind of data layer (possible more than one) under the view model. This could be an API that the view model calls, or the app could have a local database. And the view model keeps that separate from the controller and views.
On a slightly unrelated side note, I also prefer to have my controllers as swift and .xib files, rather than using a storyboard, when possible. I find big story boards tend to get very slow and eventually become tedious to make changes to. You can also then initialise the controllers like i did in the example, and don't need to create a storyboard object first. But this is just personal preference.
Upvotes: 1