NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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)

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() {

    var body: some View {

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

        .navigationBarTitle("New piggy bank space", displayMode: .inline)
        .navigationBarItems(leading: Button("Cancel",action: {self.isPresented = false}), trailing: Button("Save",action: {
            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) {

Can someone helps me?


Hacking with Swift is sponsored by Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

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.