I have the following view which displays notifications to the user:
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()
}
}
However, the delete method is not working. Whilst the row temporarily disappears, it immediately comes back into view. What am I doing wrong here?
Code for UploadNotificationManager class:
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)"
}
}
}
question from:
https://stackoverflow.com/questions/65848934/swiftui-deleted-row-from-list-keeps-re-appearing 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…