【问题标题】:Swift - UISearchBar no result message shows up when there is no dataSwift - 没有数据时 UISearchBar 不显示结果消息
【发布时间】:2020-03-03 15:25:59
【问题描述】:

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

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

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

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

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

我还检查了无数关于 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.", 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


    【解决方案1】:

    简单的逻辑可以根据你的问题在这里整合

    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
    }
    

    【讨论】:

      【解决方案2】:

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

      没有看到你的搜索条码:

      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

      【讨论】:

      • 我收到“'使用未解析的标识符'searchController'”错误,我应该在哪里声明它,或者它不应该已经在 UISearchBarDelegate 类中,因为它已经被引用了?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      相关资源
      最近更新 更多