Home > Mobile >  Remove TextField button
Remove TextField button

Time:11-22

I have this simple code, but at this moment we only have one button, which is responsible for adding new TextField. How can I make second button which will be responsible for removing last generated TextField? I totally have no idea.

import SwiftUI



struct Test : View {
    @State var ingredientNames = [""] 
    
    var body: some View {
        VStack { /// vertical stack of ingredients
            ForEach(ingredientNames.indices, id: \.self) { index in
                TextField("Name", text: $ingredientNames[index])
            }
            
            Button(action: {
                ingredientNames.append("")
            }) {
                Image(systemName: "plus.circle")
                    .foregroundColor(Color.black)
                Image(systemName: "minus.circle")
                    .foregroundColor(Color.black)
            }
        }
    }
}

CodePudding user response:

You can put the other icon into another button, and remove the last added text field by removing items off the end of the ingredientNames.

I also added a guard statement, so users don't accidentally delete from an empty list, which would cause an error.

struct Test : View {
    @State var ingredientNames = [""]
    
    var body: some View {
        VStack { /// vertical stack of ingredients
            ForEach(ingredientNames.indices, id: \.self) { index in
                TextField("Name", text: $ingredientNames[index])
            }
            
            Button(action: {
                ingredientNames.append("")
            }) {
                Image(systemName: "plus.circle")
                    .foregroundColor(Color.black)
            }
            
            Button(action: {
                guard !ingredientNames.isEmpty else {
                    print("no items to remove")
                    return
                }
                ingredientNames.removeLast()
            }) {
                Image(systemName: "minus.circle")
                    .foregroundColor(Color.black)
            }
        }
    }
}

  • Related