-1

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")

4
  • Your code works well for me, I get additional Update every 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 for UpdateStore and how you declare updates in it. Commented Mar 8, 2023 at 7:56
  • What is UpdateStore? It requires a @Published property updates to refresh the view. And please use @StateObject rather than @ObservedObjectto initialize a source of truth. If you are new to SwiftUI you certainly don't want to use outdated terminology. Commented Mar 8, 2023 at 8:00
  • Check UpdateStore file at the end Commented Mar 8, 2023 at 8:23
  • as mentioned, use @Published var updates: [Update] = [] and @StateObject var store = ... Commented Mar 8, 2023 at 8:37

1 Answer 1

0

Seems to work fine for me. Do you have @Published set on your Update? Also some minor tweaks in the view initialisation. You can not pass a view variable in to the class on init.

class UpdateStore: ObservableObject {

@Published var updates: [Update] = []

}

struct UpdateList : View {
var updates = updateData
@ObservedObject var store = UpdateStore()
//**Update func that 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: EmptyView()) {
                    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.blue)
                    }
                    .padding(8)
                    .background(Color("background3"))
                    .cornerRadius(8)
                    EditButton()
                }
            }
        }
    }
    
}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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