Design Patterns that will be covered in this article:
- Model-View-Controller
- Model
- Models hold onto application data (typically in the form of structs or simple classes)
- View
- Views communicate to their controller via IBActions
- View Controller
- Controllers coordinate between models and views
- Models and views should not hold strong references to their owning controller because this would cause a retain cycle
- Use the MVC design pattern as a starting point and be open to implementing other patterns as you build your app
- When implementing a MVC design pattern, it's convenient to organize your app bundle's files with a Model, View, and Controller directory.
- I created a simple struct that represents a single programmer
- I created an IBOutlet for each of the properties I have in the Programmer model
- I set the class of the default UIView element to the view I set-up programmatically (ProgrammerView).
- I dragged 3 UITextFields from our Object Library and placed it within the UIView.
- Go ahead and connect the 3 UITextFields with the IBOutlets using the Connection Inspector of the UIView.
- Make sure to set Auto Layout constraints for your UI elements.
- In your main view controller, you can hold a strong reference to the view and model that it owns.
- It's the controller's job to coordinate between the model and view.
- In this case, the controller should update its view using the values from the model.
public var programmer: Programmer? {
didSet {
updateViewFromProgrammer()
}
}
- If a programmer is set after viewDidLoad() is called, the controller should update ProgrammerView.
- You can use a didSet to accomplish this.
- This is an example of how the model can tell the controller that something has changed and that the view needs updating.
- Conversely, this is an example of how the view can tell the controller that something has changed and the model needs updating.
- I connected the IBAction to all three of the textfields in Main.storyboard.
- To see the IBAction work with a UITextField, I connected each of the textfields to the same IBAction with an Editing Changed event.