Swiftui 列表更新问题

时间:2021-06-26 23:37:48

标签: listview swiftui observable

//附加的数据实际上是来自推送通知的数据,它会在列表视图中附加新的通知 问题是,更新数组中的数据后,即使日期已成功添加到数组中,视图也不会更新。//

//这里是我的观点和方法//

struct ContentView: View {

    
    @ObservedObject var notification = OnlyNotification()
    
    var body: some View {
        NavigationView{
                List{
                    ForEach(notification.data, id: \.id){ Message in
                    NotificationCell(Message:Message)
                }
            }
        }
    }
}

struct NotificationCell: View {
    let Message:MyNotification
    var body: some View {
        NavigationLink(destination: Text(Message.name)){
            Image(Message.imageName)
                .cornerRadius(40)
                .overlay(RoundedRectangle(cornerRadius: 40)
                            .stroke(Color.gray, lineWidth: 1))
            VStack(alignment: .leading) {
                Text(Message.name)
                    .font(.headline)
                Text(Message.ImageLink)
                    .font(.subheadline)
                    .foregroundColor(Color.gray)
            }
        }.navigationBarTitle(Message.name)
    }
}
struct MyNotification:Identifiable {
    var id = UUID()
    var name:String
    var ImageLink:String
    var Message:String
    var imageName:String {return name}
    
}
class OnlyNotification: ObservableObject{
    @Published var data = [MyNotification]()
    init() {
        let notification1 = MyNotification(name: "Rafael Nadal", ImageLink: "New", Message: "Hi Budy")
        addnotification(Data: notification1)
    }
    public func addnotification(Data:MyNotification){
        self.data.insert(MyNotification(name: Data.name, ImageLink: Data.ImageLink, Message: Data.Message), at: 0)
    }
    public func getData() ->[MyNotification] {
        return data
    }
    
}

// 从 AppDelegate 追加项目// 让 obj = OnlyNotification()

 obj.addnotification(Data: MyNotification(name: "\(notification.request.content.userInfo["Name"]!)", ImageLink: "New", Message: "\(notification.request.content.userInfo["Message"]!)"))

2 个答案:

答案 0 :(得分:0)

您正在显示来自“ContentView @ObservedObject var notification = OnlyNotification()”的数据, 但是在您的代码中的其他地方,您正在使用另一个“let obj = OnlyNotification()”并添加到其中。 它们是不同的对象。

答案 1 :(得分:0)

全局声明类外的对象

var Myinstance:OnlyNotification?

然后在类的初始化器中 这样做

Myinstance = self

然后在任何地方访问这个全局实例来访问同一个实例的类的函数和对象

相关问题