Swift-UISearchBar没有数据时不会显示结果消息

我有一个 UISearchBar 过滤器,该过滤器运行良好,并且可以从我的 CoreData 数据库中的 UITableView 中正确找到数据。

当找不到匹配的文本时,它也可以正确显示,然后在匹配时消失,并显示数据。

我的问题是,当“表视图”中没有数据时,将显示“无结果”消息。

我知道问题的原因,因为当计数大于0时,我的代码不返回消息,并且由于表中没有数据,它肯定会显示该消息,但我不知道如何解决此问题

有人可以为我提供一种方法,以便在搜索文本后立即弹出无结果消息,然后在不使用搜索栏时将其关闭吗?

我也检查了无数有关Stack Overflow的相关问题,但没有一个满足我的需求。

屏幕截图

Picture of the issue

如您所见,它显示的是消息,甚至没有使用 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()
}
j5210 回答:Swift-UISearchBar没有数据时不会显示结果消息

似乎没有数据时,您的coreDataVariable.count为0。因此,没有行,并且您的标签上显示的内容是“未找到查询。\ n \ n请检查您的搜索”。我相信coreDataVariable会在被搜索之前包含所有数据。您还需要一些已排序的filteredDat

没有看到您的searchBar代码:

override func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int
{
    if searchController.isActive &&  searchController.searchBar.text != ""{
        // check your filtered data count here and if it is 0,show your label
        // Do the logic and find how many rows you need
    }
}

经验法则,当tableView具有SearchBar时,那么NumberOfSection,NumebrOfRow,CellForRow需要:

if searchController.isActive &&  searchController.searchBar.text != ""{
        //Your logic here
}

2019年11月7日更新: 在代码中的某处定义此

let searchController = UISearchController(searchResultsController: nil)

确保您的班级符合UISearchResultsUpdatingUISearchBarDelegate 另外这可能会有所帮助 https://stackoverflow.com/a/28997222/1200543

,

可以根据您的问题在此处集成简单的逻辑

var isSearchActive = false // bool variable

func searchBar(_ searchBar: UISearchBar,textDidChange searchText: String)
{
  if self.searchBar.text == ""
  {
        isSearchActive = false 
       //--               
  }
  else
   {
        isSearchActive = true
   }

    self.tableView.reloadData()
  }

 //logic  this  data source method
 func numberOfSections(in tableView: UITableView) -> Int
 {
 if coreDataVariable.count > 0 {
   self.tableView.backgroundView = nil
   self.tableView.separatorStyle = .singleLine
    return 1
 }
 else 
 { 
    if isSearchActive == true
    {
       // -- Make UIlabel here
    }
}
override func tableView(_ tableView: UITableView,numberOfRowsInSection  section: Int) -> Int
{
return coreDataVariable.count
}
本文链接:https://www.f2er.com/3147461.html

大家都在问