【发布时间】:2020-03-03 15:25:59
【问题描述】:
我有一个 UISearchBar 过滤器,它运行良好,可以从我的 CoreData 数据库中正确找到我的 UITableView 中的数据。
当它没有找到匹配的文本时它也会正确显示,然后在匹配时消失并显示数据。
我的问题是当表格视图中没有数据时显示无结果消息。
我知道问题的原因,因为我的代码在计数大于 0 时没有返回消息,并且由于表中没有数据,它肯定会显示消息,但我不知道如何解决这个问题.
有人可以指导我一种方法,以便在搜索文本后立即弹出无结果消息only,然后在不使用搜索栏时将其关闭?
我还检查了无数关于 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.", 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("Error loading data")
}
}
table.reloadData()
}
【问题讨论】:
标签: ios swift uitableview core-data uisearchbar