My code is a little more complex than this so I created an example that gets the same error.
When I navigate into a view, I have a function I want to perform with a variable passed into this view. That function then produces an array. I then want to put that array into a List, but I get an error.
How do I get the List to show the produced array?
I think the issue is the List can't be updated because it already has the declared blank array.
struct ContentView : View {
@State var array = [String]()
var body: some View {
List(self.array,id: \.self) { item in
Text("\(item)")
}
.onAppear(perform: createArrayItems)
}
func createArrayItems() {
array = ["item1", "item2", "item3", "item4", "item5"]
}
}
To add the pull to refresh functionality to our SwiftUI List, simply use the . refreshable modifier. List(emojiSet, id: \. self) { emoji in Text(emoji) } .
The rows in a list can be added by clicking the plus icon in the navigation bar.
To begin, create a SwiftUI Xcode project, and create a struct , namely, Data . Let's get back in our ContentView. swift and populate some values into this struct . Now, inside your view, create a List, and use ForEach to add and see all your data in list form.
SwiftUI displays the search bar under the navigation bar title and above the list that you'll filter. In multi-column view, you can choose in which view to display your search bar.
You can use ObservableObject data providers(eg : ViewModel) with @Published properties.
struct ListView: View {
@ObservedObject var viewModel = ListViewModel()
var body: some View {
NavigationView {
List(){
ForEach(viewModel.items) { item in
Text(item)
}
}
}
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ListView()
}
}
#endif
class ListViewModel: ObservableObject {
@Published var items = ["item1", "item2", "item3", "item4", "item5","item6"]
func addItem(){
items.append("item7")
}
}
@txagPman
I too have your problem to understand how to modify a list. I was able to write this code. I hope it's useful.
import SwiftUI
struct ContentView: View {
@State private var array = createArrayItems()
// @State private var array = [""] - This work
// @State private var array = [] - This not work
@State private var text = ""
var body: some View {
VStack {
TextField("Text", text: $text, onCommit: {
// self.array = createArrayItems() - This work after press return on textfield
self.array.append(self.text)
}).padding()
List (self.array, id: \.self) {item in
Text("\(item)")
}
}
// .onAppear {
// self.array = createArrayItems() - This not work
// }
}
}
func createArrayItems() -> [String] {
return ["item_01","item_02","item_03","item_04" ]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With