我在视图中有一个条目列表。该视图顶部还有一个搜索栏。进行搜索时,搜索结果会正确显示。现在显示搜索结果后,我删除其中一个条目。这也很好。但是,当我开始删除在搜索字段中输入的搜索字符时,只显示删除和编辑图标的虚拟字段(与删除的条目相关),如此显示...
此处删除的记录仍然显示为空,但根本不应显示。
这是我在搜索栏textDidChange
中编写的代码......
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText != "" {
charInSearchBar = true
//filter the results
searchActive = true
filtered = self.allCategories.filter({( data : CategoryItems) -> Bool in
if let sdf = data.category {
return (sdf.lowercased().contains(searchText.lowercased()))
}
return false
})
if(filtered.count == 0){
noSearchChar1 = true
noSearchChar = true
} else {
searchActive = true
}
tableview.reloadData()
}
else {
noSearchChar1 = false
searchActive = false
self.tableview.reloadData()
}
}
编辑1
这是删除行的方法......
func deleteTapped(cell: ProductCategoryTableViewCell) {
if let indexPath = tableview?.indexPath(for: cell) {
if (searchActive) {
deleteBtnTapped = true
let alertController = UIAlertController(title: "Alert", message: "Delete this Category?", preferredStyle: UIAlertControllerStyle.alert)
let yesAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
context.delete(self.filtered[indexPath.row] as NSManagedObject)
self.filtered.remove(at: indexPath.row)
// try context.save()
do {
try context.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
self.tableview.deleteRows(at: [indexPath], with: .fade)
self.tableview.reloadData()
self.deleteBtnTapped = false
}
}
}
答案 0 :(得分:0)
您不仅要从filtered
删除该项目,还要从self.allCategories
删除该项目。
context.delete(self.filtered[indexPath.row] as NSManagedObject)
// here remove it from allCategories as well
if let indexInAllCategories = self.allCategories.index(of: self.filtered[indexPath.row]) {
self.allCategories.remove(at: indexInAllCategories)
}
self.filtered.remove(at: indexPath.row)