NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

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?

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.