搜索栏为空或 nil 时表格为空

Posted

技术标签:

【中文标题】搜索栏为空或 nil 时表格为空【英文标题】:Table is empty when search bar is empty or nil 【发布时间】:2017-08-10 22:15:35 【问题描述】:

当我搜索商店时,桌子会找到正确的商店。但是当我编辑我的搜索词(例如删除一个字母)时,表格变为空。即使我删除了搜索词,表格也会变成空的!我必须转到不同的视图控制器并返回搜索栏才能查看完整的表格。

这是我的代码

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) 

    shops = shops.filter  $0.shopname.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil


    tableView.reloadData()


我应该在哪里实现if searchBar.text == "" || searchBar.text ==nill 返回原始表格单元格。或者当再次搜索时,我希望它执行另一次搜索。

更新

我的商店数组不是字符串类型,而是其中包含字符串的类类型。因为它是一个自定义单元格,其中包含来自 api 的 JSON 数据

 var shops: [Shops]!
var isSearch = false
var auxiliar : [String] = []
var searchActive: Bool = false



class Shops 
private var _familiy_id: String?
private var _logo : String?

private var _shopname : String?

var familiy_id : String
    return _familiy_id!


   var shopname : String
    return _shopname!

var Logo : String
    return _logo!

init(shopname : String , Logo : String , family_id : String) 

    self._shopname = shopname
           self._logo = Logo
    self._familiy_id = family_id

【问题讨论】:

【参考方案1】:

问题出在这一行:

shops = shops.filter   ... 

由于您只是应用过滤器并与原始数组重叠,因此您将丢失元素。需要一个辅助数组来帮助保留原始数组。

一个简单的例子:(代码更新)

import UIKit

class Shops 
    private var _familiy_id: String?
    private var _logo : String?
    private var _shopname : String?

    var familiy_id : String
        return _familiy_id!
    

    var shopname : String
        return _shopname!
    
    var Logo : String
        return _logo!
    
    init(shopname : String , Logo : String , family_id : String) 
        self._shopname = shopname
        self._logo = Logo
        self._familiy_id = family_id
    




class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate 
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!

    var shops : [Shops]! = []
    var auxiliar : [Shops]!

    override func viewDidLoad() 
        super.viewDidLoad()
        // 1 - load data to shops array
        shops.append(Shops(shopname: "Brasil", Logo: "BR", family_id: "1"))
        shops.append(Shops(shopname: "Brasolia", Logo: "BA", family_id: "2"))
        shops.append(Shops(shopname: "Colombia", Logo: "CO", family_id: "3"))
        shops.append(Shops(shopname: "Argentina", Logo: "AR", family_id: "4"))




        // 2  - auxiliar receive the complete original array
        auxiliar = shops

        // Do any additional setup after loading the view, typically from a nib.
    

    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
        return auxiliar.count;
    

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        cell.textLabel?.text = auxiliar[indexPath.row].shopname
        return cell
    

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) 
         auxiliar = shops.filter  $0.shopname.range(of: searchText, options: .caseInsensitive, range: nil, locale: nil) != nil 
        if searchText == "" 
            // 3 if there is nothing to search, auxiliar receive the complete orihinal array
            auxiliar = shops
        

        tableView.reloadData()
    

【讨论】:

您能否检查我更新的问题以查看我的商店数组的错误 没问题,只需将辅助声明为 var auxiliar : [Shops]!并使用您正在使用的过滤器表单。 问题是let temp: NSString = text as NSString中的text 谢谢 :) 迫不及待想看看这个问题是如何解决的 shops has no member range`这实际上是错误【参考方案2】:

Swift 3 中,您可以使用这样的代码。您只需尝试此代码即可。

import UIKit

class SearchBarTableView: UIViewController, UITableViewDataSource,UITableViewDelegate, UISearchBarDelegate 

  @IBOutlet weak var tableView: UITableView!
  @IBOutlet weak var searchBar: UISearchBar!

  var shops : [String] = ["Brasil", "Argentina", "Colombia", "Chile", "Equador", "Peru", "Uruguai", "Paraguai", "Venezuela"];
  var auxiliar : [String] = []
  var searchActive: Bool = false

  override func viewDidLoad()
  
      super.viewDidLoad()
      self.tableView.dataSource = self
      self.tableView.delegate = self
      self.searchBar.delegate = self
  

  func searchBarTextDidBeginEditing(_ searchBar: UISearchBar)
  
      self.searchActive = true
  

  func searchBarTextDidEndEditing(_ searchBar: UISearchBar)
  
      self.searchActive = false
  

  func searchBarCancelButtonClicked(_ searchBar: UISearchBar)
  
      self.searchActive = false
  

  func searchBarSearchButtonClicked(_ searchBar: UISearchBar)
  
      self.searchActive = false
  

  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
  
      self.auxiliar = self.shops.filter( (text) -> Bool in
      let temp: NSString = text as NSString
      let range = temp.range(of: searchText, options:.caseInsensitive)
     return range.location != NSNotFound
     )

      if self.auxiliar.count == 0
      
          searchActive = false
      
      else
      
          searchActive = true
      
      self.tableView.reloadData()
  


  func numberOfSections(in tableView: UITableView) -> Int 
    return 1
  

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
      if searchActive
      
      return auxiliar.count
      
      return shops.count
   

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
      let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
      if searchActive
      
          cell.textLabel?.text = auxiliar[indexPath.row]
      
      else
      
          cell.textLabel?.text = shops[indexPath.row]
        
      return cell
  

【讨论】:

感谢您的回答。您能否查看我更新的问题以查看由于我的 shop 数组类型而导致的错误

以上是关于搜索栏为空或 nil 时表格为空的主要内容,如果未能解决你的问题,请参考以下文章

如何在 iOS 中检查 NSArray 是不是为空或为空?

UISearchController:即使搜索栏为空也显示结果

检查所有三列是不是不为空或为空

当值为空或为空时如何返回默认值

BigQuery bq 命令 - 仅在表为空或不存在时加载

如何从 nsmutabledictionary 中删除键当该键的值在 ios 中为空或 null 时?