我有以下视图向用户显示通知:
struct NotificationContentView: View {
@State private var notifications = UploadNotificationManager.shared.notifications
let appDelegate = UIApplication.shared.delegate as! AppDelegate
private lazy var context: NSManagedObjectContext = {
return appDelegate.persistentContainer.viewContext
}()
var body: some View {
List {
if let notifications = UploadNotificationManager.shared.notifications {
ForEach(notifications, id: \.self) { notification in
if let text = UploadNotificationManager.shared.notificationText(notifcation: notification) {
VStack(alignment: .trailing, spacing: 6) {
HStack {
Image(systemName: "xmark.circle.fill").foregroundColor(Color(UIColor.i6.alert))
Text(text).font(.system(size: 14))
}
Text("3 mins ago").font(.system(size: 10)).foregroundColor(Color(UIColor.i6.blue.withAlphaComponent(0.8)))
}
}
}
.onDelete(perform: delete)
}
}.cornerRadius(15).shadow(radius: 5).shadow(color: .gray, radius: 3, x: 2, y: 2).frame(width: 400, height: 350, alignment: .center)
}
func delete(at offsets: IndexSet) {
guard let index = Array(offsets).first else { return }
notifications?.remove(at: index)
notifications![0].dismissed = true
appDelegate.saveContext()
}
}
但是,删除方法不起作用。虽然该行暂时消失,但它会立即重新出现。我在这里做错了什么?
UploadNotificationManager 类的代码:
class UploadNotificationManager {
var notifications: [UploadNotificationCD]?
let appDelegate = UIApplication.shared.delegate as! AppDelegate
static let shared = UploadNotificationManager()
init() {
getNotifications()
}
func getNotifications() {
let context = appDelegate.persistentContainer.viewContext
notifications = context.fetch(UploadNotificationCD.self)
}
func notificationText(notifcation: UploadNotificationCD) -> String? {
guard let code = notifcation.fuelSheet?.flightNumber else { return nil }
if notifcation.flightValid == false {
return "Unable to create order for flight \(code) - invalid flight"
} else if notifcation.successfullyUploaded == false {
return "Unable to create order for flight \(code)"
} else {
return "Successfully uploaded order for flight \(code)"
}
}
}