WWDC21 SALE: Save 50% on all my Swift books and bundles! >>

Appending content using MVVM pattern with SwiftUI

Forums > SwiftUI

I've a problem. So, I've a View to add a new content on my app, I've a Model and a ViewModel.

  1. is it possible to use Model for two-way binding?(on the form)
  2. How to collect all the form data and append it to all the available Goals? knowing that some of the Model property will be empty

I don't know how to do that. Here my view

import SwiftUI

#if canImport(UIKit)
extension UIApplication {
    func endEditing() {
        sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}
#endif

struct NewGoalView: View {
    @State private var categories = ["Health and hospital bills", "Food", "Clothing/Fashion", "Electronics/Smart devices", "Transportation", "Investment", "Rent", "Fees", "Payoff debts", "Start business", "Emergency", "Others"]
    @State private var category:Int = 0
    @State private var projectName:String = ""
    @State private var amount:String = ""
    @State private var duration:Date = Date()
    @State private var interest:Bool = true
// Alert or modal presentation variables
    @Binding var isPresented: Bool
    @State var showAlert: Bool = false

    private func endEditing() {
        UIApplication.shared.endEditing()
    }

    var body: some View {

        Form{
            Section{
                Text("Pick a category for your goal").foregroundColor(.secondary)
                Picker("Category", selection: $category){
                    ForEach(0..<categories.count, id: \.self){
                        Text(categories[$0]).tag($0)
                    }
                }
            }
            Section{
                TextField("Your goal name", text: $projectName)
                TextField("The amount you want to raise", text: $amount)
                    .keyboardType(.numberPad)
            }
            Section{
                Text("When do you want to achieve it?").foregroundColor(.secondary)
                DatePicker("Duration", selection: $duration, in:Date()..., displayedComponents: [.date]).datePickerStyle(GraphicalDatePickerStyle())
            }
            Section{
                Toggle("Interest on saving", isOn: $interest)
            }
        }.gesture(DragGesture().onChanged({ (value) in
            self.endEditing()
        }))

        .navigationBarTitle("New piggy bank space", displayMode: .inline)
        .navigationBarItems(leading: Button("Cancel",action: {self.isPresented = false}), trailing: Button("Save",action: {
            print("Saved")
            showAlert =  true
        }).alert(isPresented: $showAlert){
            Alert(title: Text("Success"), message: Text("You've successfully set your new goal"), dismissButton: .default(Text("Got it!")){
                self.isPresented = false
            })
        })
    }
}

struct NewGoalView_Previews: PreviewProvider {
    static var previews: some View {
        NewGoalView(isPresented: .constant(false))
    }
}

My Model

struct Goal: Identifiable {
    var id = UUID
    var name: String
    var amount: Double  
    var raised: Double
    var priority: String
    var status: String
    var image: String
}

My ViewModel

class GoalViewModel:ObservableObject {
    @Published var goals: [Goal] = [
        .init(id: UUID(), name: "MacBook Pro", amount: 900000.00, raised: 234000, priority: "high", status: "in process", image: "macbook"),
        .init(id: UUID(), name: "iPad Pro", amount: 780000.00, raised: 380000, priority: "high", status: "in process", image: "ipad"),
        .init(id: UUID(), name: "AirPods Pro", amount: 180000.00, raised: 150000, priority: "high", status: "in process", image: "airpods")
    ]

    func create(goal: Goal) {
        goals.append(goal)
    }
}

Can someone helps me?

   

Save money with our WWDC sale!

SAVE 50% To celebrate WWDC21, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.