UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SwiftUI: How to bind separate amounts to each instance of a dynamic view?

Forums > SwiftUI

I have a dynamic SwiftUI view (SingleMember) that represents individual members. Each instance of this view needs to have its own separate amount value, which the user can enter through a TextField. I want to bind these individual amounts to the corresponding members in an array in my view model (ViewModel). How can I achieve this binding and update the array with the respective amounts when a button is clicked?

This is on ViewModel:

@Published var amounts: [String] = []

This is my single member

struct SingleMember: View {
    @ObservedObject var groupAirtimeVM: GroupAirtimeViewModel
    @State var memberItem: MemberInfo
    @State var amount: String = ""

    var body: some View {
        VStack(alignment:.leading){
            Divider()
            HStack{
                Image("avatar")
                VStack(alignment:.leading){
                    Text("\(memberItem.firstName ?? "Unknown")")
                        .font(.custom("Ubuntu-Regular", size:15))
                    Text("\(memberItem.phoneNumber ?? "Unknown")")
                        .font(.custom("Ubuntu-Regular", size:12))
                        .foregroundColor(.gray)
                }
                Spacer()
                HStack{
                    TextField("Amount", text: $amount)

                        .frame(width:50)
                        .background(.clear)

                    Image(systemName: "square.and.pencil")
                }.font(.custom("Ubuntu-Regular", size: 12))
                    .foregroundColor(Color.gray)

            }
      }
  }
}

this is my dynamic view

 ScrollView {
       ForEach(memberInfo, id:\.self){ item in
        SingleMember(groupAirtimeVM: groupAirtimeVM, memberItem: item)
 } 
 .background(Color.white)
 .scrollContentBackground(.hidden)
 .tint(Color.gray.opacity(0.4))
 .padding(.bottom, 15)

   Button("Add Amount To Array"){
   //action where should add to array
   }

}

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

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.