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

Dynamic Textfield

Forums > SwiftUI

Hello, I would to add new HStack in view if I click button

struct Test: View {
    @State private var wordOne = ""
    @State private var wordTwo = ""
    @State private var howManyWords = 1
    var body: some View{
                ForEach(0..<howManyWords){_ in
                    HStack(spacing: 5){
                        TextField("word 1", text: $wordOne)
                        TextField("word 2", text: $wordTwo)

                Button("Add word"){
                    howManyWords += 1

I trying this way but view is not refresh. Thank for help.



Each textfield needs it's own state variable to bind to.

this seems to be similar to what you are trying to do but with only one textfield per row:


in terms of having a pair of textfields in each row - you could define an array of tuples containing (string, string) although it depends on what you are planning to do with all these textfields once the user has filled them in? Suppose you could then flatten that array back out again once user has filled in the textfields - so the values aren't in tuple pairs (I am sure this is probably not a good way of doing this but it's one way I can think of which works).

I think latest xcode and IOS builds allow more "grid type" functionality with lazyVStack and lazyHStack but I've not looked into those in any way.



If you look in the console (at the bottom of Xcode) you will find it is telling you what the issue is... you need to add the id

ForEach(0..<howManyWords, id: \.self) { _ in

However, as mentioned by @rlong405 each TextField requires a binding to an @State property. if you share these with multiple textfields you will get some problems.

If what you want is just a new HStack, that contains anything other than a textfield, then adding the id will be enough.

Otherwise, it will be too much of a pain... If you share why you are trying to do that, we might be able to help you find a solution that works.


Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot 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.