I can't dynamically add items to List. SwiftUI.
import SwiftUI
struct UpdateList : View {
var updates = updateData
@ObservedObject var store = UpdateStore(updates: updateData)
**Update func doesn't work(It doesn't add anything)**
func addUpdate() {
store.updates.append(Update(image: "Certificate1", title: "New Title", text: "New Text", date: "JUL 1"))
}
func move(from source: IndexSet, to destination: Int) {
store.updates.swapAt(source.first!, destination)
}
var body: some View {
NavigationView {
**List Code**
List {
ForEach(store.updates) { item in
NavigationLink(destination: UpdateDetail(title: item.title, image: item.image, text: item.text)) {
HStack(spacing: 12.0) {
Image(item.image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 80, height: 80)
.background(Color("background"))
.cornerRadius(20)
VStack(alignment: .leading) {
Text(item.title)
.font(.headline)
Text(item.text)
.lineLimit(2)
.lineSpacing(4)
.font(.subheadline)
.frame(height: 40.0)
Text(item.date)
.font(.caption)
.fontWeight(.bold)
.foregroundColor(Color.gray)
}
}
}
.padding(.vertical, 8.0)
}
.onDelete { index in
self.store.updates.remove(at: index.first!)
}
.onMove(perform: move)
}
.navigationBarTitle(Text("Updates"))
.toolbar{
ToolbarItem{
HStack {
Button(action: addUpdate) {
Text("Add Update")
.foregroundColor(Color.white)
}
.padding(8)
.background(Color("background3"))
.cornerRadius(8)
EditButton()
}
}
}
}
}
}
struct UpdateList_Previews : PreviewProvider {
static var previews: some View {
UpdateList()
}
}
struct Update: Identifiable {
var id = UUID()
var image: String
var title: String
var text: String
var date: String
}
var updateData = [
Update(image: "Illustration1", title: "SwiftUI", text: "Learn how to build custom views and controls in SwiftUI with advanced composition, layout, graphics, and animation. See a demo of a high performance, animatable control and watch it made step by step in code. Gain a deeper understanding of the layout system of SwiftUI.", date: "JUN 26")
UpdateStore file
import SwiftUI
import Combine
class UpdateStore : ObservableObject {
var didChange = PassthroughSubject<Void, Never>()
var updates: [Update] {
didSet{
didChange.send()
}
}
init(updates: [Update] = []) {
self.updates = updates
}
}
I'm expecting add a new list item everytime I tap the button("Add Update")
Updateevery time I click the "Add Update" Button. On MacOS 13.3, Xcode 14.3 beta, tested on real ios 16.3 devices (not Previews), and macCatalyst. It could be different on older systems. I would suggest using@StateObject var store .... Can you show the code forUpdateStoreand how you declareupdatesin it.UpdateStore? It requires a@Publishedpropertyupdatesto refresh the view. And please use@StateObjectrather than@ObservedObjectto initialize a source of truth. If you are new to SwiftUI you certainly don't want to use outdated terminology.@Published var updates: [Update] = []and@StateObject var store = ...