我有一个 UISearchBar 过滤器,该过滤器运行良好,并且可以从我的 CoreData 数据库中的 UITableView 中正确找到数据。
当找不到匹配的文本时,它也可以正确显示,然后在匹配时消失,并显示数据。
我的问题是,当“表视图”中没有数据时,将显示“无结果”消息。
我知道问题的原因,因为当计数大于0时,我的代码不返回消息,并且由于表中没有数据,它肯定会显示该消息,但我不知道如何解决此问题
有人可以为我提供一种方法,以便在搜索文本后立即弹出无结果消息仅,然后在不使用搜索栏时将其关闭吗?
我也检查了无数有关Stack Overflow的相关问题,但没有一个满足我的需求。
屏幕截图
如您所见,它显示的是消息,甚至没有使用 UISearchBar 。
代码
override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int
{
if coreDataVariable.count > 0 {
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .singleLine
return 1
}
let rect = CGRect(x: 0,y: 0,width: self.tableView.bounds.size.width,height: self.tableView.bounds.size.height)
let noDataLabel: UILabel = UILabel(frame: rect)
noDataLabel.numberOfLines = 0
noDataLabel.text = "Query not found.\n\nPlease check your search."
noDataLabel.textAlignment = NSTextAlignment.center
self.tableView.backgroundView = noDataLabel
self.tableView.separatorStyle = .none
return coreDataVariable.count
}
这是我的搜索栏功能
func searchBar(_ searchBar: UISearchBar,textDidChange searchText: String) {
if !searchText.isEmpty
{
var predicate: NSPredicate = NSPredicate()
predicate = NSPredicate(format: "attriubteName1 contains[c] '\(searchText)' OR attriubteName2 contains[c] '\(searchText)'")
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedobjectcontext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
fetchRequest.predicate = predicate
do
{
coreDataVariable = try managedobjectcontext.fetch(fetchRequest) as! [NSManagedObject] as! [objectname]
}
catch let error as NSError
{
let alert = UIAlertController(title: "Cannot Search Data",message: "Error searching saved data. Please reinstall objectname Saver if problem persists.",preferredStyle: UIAlertController.Style.alert)
let okaction = UIAlertaction(title: "OK",style: UIAlertaction.Style.cancel)
{
UIAlertaction in
alert.removeFromParent()
}
alert.addaction(okaction)
self.present(alert,animated: true,completion: nil)
print("Could not fetch. \(error)")
}
}
else
{
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedobjectcontext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "objectname")
do
{
coreDataVariable = try managedobjectcontext.fetch(fetchRequest) as! [objectname]
}
catch
{
let alert = UIAlertController(title: "Cannot Load Data",message: "Error loading saved data. Please app if problem persists.",style: UIAlertaction.Style.cancel) {
UIAlertaction in
alert.removeFromParent()
}
alert.addaction(okaction)
self.present(alert,completion: nil)
print("Error loading data")
}
}
table.reloadData()
}