删除 UITableView 行时删除通知 (Swift)



我有一个带有多个UITableviews的视图控制器。我希望从表视图中删除一行以删除与此行关联的通知,这是我的代码,但我收到错误Index out of range如果有人想测试它,这里是指向我的项目的链接:https://files.fm/f/nwx8e7je

我的代码:它无需简单的字符串即可工作,但对于索引行,我得到了错误。

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if tableView == ScheduleTableView{

let defaults = UserDefaults.standard
var myarray = defaults.stringArray(forKey: "ScheduleArray") ?? [String]()
var myarray2 = defaults.stringArray(forKey: "ScheduleTimeArray") ?? [String]()
// Remove Row
myarray.remove(at: indexPath.row)
myarray2.remove(at: indexPath.row)
defaults.set(myarray, forKey: "ScheduleArray")
defaults.set(myarray2, forKey: "ScheduleTimeArray")
ScheduleTableView.deleteRows(at: [indexPath], with: .fade)
UserDefaults.standard.synchronize()

// Remove Notification
let center = UNUserNotificationCenter.current()
let arrayToSearch = myarray[indexPath.row] as String
center.getPendingNotificationRequests { (notifications) in
for item in notifications {
if(item.identifier.contains(arrayToSearch)) {
center.removePendingNotificationRequests(withIdentifiers: [item.identifier])
}
}
}

}
if tableView == GoalsTableView{

}
}

删除此行let arrayToSearch = myarray[indexPath.row] as String并改用已删除的项目,因为您已经在myarray.remove(at: indexPath.row)删除了项目

这是代码:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if tableView == ScheduleTableView{
// Here is my code but it gives me an error, first you need to add a row with the add button
let defaults = UserDefaults.standard
var myarray = defaults.stringArray(forKey: "ScheduleArray") ?? [String]()
print(myarray)
let removedItem =  myarray.remove(at: indexPath.row)
defaults.set(myarray, forKey: "ScheduleArray")
ScheduleTableView.deleteRows(at: [indexPath], with: .fade)
// Remove Notification
let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests { (notifications) in
for item in notifications {
if(item.identifier.contains(removedItem)) {
center.removePendingNotificationRequests(withIdentifiers: [item.identifier])
}
}
}

}
if tableView == GoalsTableView{

}
}

最新更新