dimanche 28 juin 2020

Using a design pattern like MVC with SwiftUI

I am trying to implement a design pattern like MVC in order to achieve low coupling between different parts of the code. There are few materials online that I personally didn't find helpful in relation to IOS or swift UI development and MVC pattern.

What I am trying to understand is how should the controller class control or render the UI in Swift UI ?

Following the MVC pattern for example - the View shouldn't know about how the model looks like, so sending an object back from the Data Base to the view in order to visually present it wouldn't be a good Idea..

Say we have the following View and Controller, how should I go about the interaction between the controller and view when sending the data back from the DB in order to visually present it in the view ?

View:

import SwiftUI
import Foundation

struct SwiftUIView: View {

    
    var assignmentController = AssignmentController()
    

    @State var assignmentName : String = ""
    @State var notes : String = ""
  

  
    var body: some View {
        
        NavigationView {
            VStack {
                Form {
                   
                        
                        TextField("Assignment Name", text: $assignmentName)

    
                        TextField("Notes", text: $notes)
                
     
            }
                
                Button(action: {
                                                               
                    self.assignmentController.retrieveFirstAssignment()
                                       }) {
                                                                                                                                                Text("Get The First Assignment !")
                                                                                    }

            }
            .navigationBarTitle("First Assignment")
        }
        
    
}
}

Controller

var assignmentModel = AssignmentModel()

func retrieveFirstAssignment()
{
    var firstAssignment : Assignment

    firstAssignment=assignmentModel.retrieveFirstAssignment()
    
}

For now, it does nothing with the object it found.

Model

An object in the model composed of two String fields : "assignmentName" and "notes".

*We assume the assignment Model have a working function that retrieves one task from the DB in order to present it in the view.

Aucun commentaire:

Enregistrer un commentaire