1

Here is my test code:

struct ArrView: View {
    @State var arr: [String] = ["first", "second"]
    var body: some View {
        VStack {
            Button("append") {self.arr.append("item\(self.arr.count)")}
            List(arr.indices) {row in
                Text(self.arr[row])
            }
        }
    }
}

When the 'append' Button was pressed, the List view didn't update. Am I doing wrong?

1
  • 2
    Try adding .id(self.arr.count) after list Commented May 27, 2020 at 15:38

2 Answers 2

2

You can use ForEach<Range>() only if the provided data is a constant, otherwise you need to use ForEach(_:id:content:) and provide an id explicitly, like this:

struct ArrView: View {
    @State var arr: [String] = ["first", "second"]
    var body: some View {
        VStack {
            Button("append") {self.arr.append("item\(self.arr.count)")}
            List(arr, id: \.self) { item in
                Text(item)
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I don't think it is the proper way to create List view. Here is a sample

struct ContentView: View {
    @State var arr: [String] = ["first", "second"]
    var body: some View {
        VStack {
            Button("append") {self.arr.append("item\(self.arr.count)")}
            List(self.arr, id: \.self) { str in
                Text(str)
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.