ios - UISearchController更新搜索结果问题

标签 ios swift3

我的问题是,当我尝试过滤它时,我已经在 Swift 3 中实现了 UISearchController 它是很容易过滤的简单数组,但我的情况有点不同,我有一个数组,我从 中获取所有数据>SQLite 数据库 在类中,因此它是类的数组

managerControlClassArray 包含类数组的所有内容。

我想过滤 updateSearchResults 委托(delegate)方法中的内容,但这确实很困难并且卡住了,我做了很多研究,在没有得到我想要的查询后,我发现 StackOverflow 非常有用,如果有人帮助的话,我会质疑它我,我将不胜感激。

一些代码逻辑:

manager = ModelManager.getInstance().getAllManager()
// I get all the objects using singleton

//manager class has following data
id, title, designation, salary

//In TableView i want to display data by using that

let managerVar = manager[indexPath.row]
cell.textLabel.text = managerVar.title

编辑:

MasterTableViewController.swift

import UIKit

class MasterTableViewController: UITableViewController, UISplitViewControllerDelegate, UISearchResultsUpdating {

      var array: NSMutableArray! = NSMutableArray()

      var managerArray = [foodManager]()

      var filteredmanagerArray = [foodManager]()
      var searchController = UISearchController(searchResultsController: nil)


  override func viewDidLoad() {
      super.viewDidLoad()

      // Set the AppTitle using Config File
      self.title = GL_Appname

      managerArray = ModelManager.getInstance().getAllManagers()

      filteredmanagerArray = managerArray

      //copyTitleArrayForSearch()

      self.tableView.reloadData()

      self.splitViewController!.delegate = self;
      self.splitViewController!.preferredDisplayMode = UISplitViewControllerDisplayMode.allVisible

      //Seach Result Controller
      self.searchController.searchResultsUpdater = self
      self.searchController.dimsBackgroundDuringPresentation = false
      self.searchController.definesPresentationContext = true
      self.searchController.searchBar.sizeToFit()
      self.tableView.tableHeaderView = self.searchController.searchBar


  }



  /* func copyTitleArrayForSearch(){

        for i in 0..<managerArray.count{
            let fd = managerArray[i]

            //titleArray.append(fd.title)
        }

    } */

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

 // MARK: - Table view data source

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

  override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
      return 60
  }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

      if searchController.isActive{
          return filteredmanagerArray.count
      }
      else{
          return managerArray.count
      }
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

      cell.textLabel?.adjustsFontSizeToFitWidth = true
      cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
      cell.textLabel?.numberOfLines = 3

      cell.textLabel?.textColor = UIColor.black
      cell.textLabel?.font = UIFont(name: "ChalkboardSE-Light", size: 14.0)

      if searchController.isActive {
          let fra = filteredmanagerArray[indexPath.row]
          cell.textLabel?.text = fra.title.uppercased()
      }
      else{
          let fd = managerArray[indexPath.row]
          cell.textLabel?.text = fd.title.uppercased()
      }

      return cell
  }

  func updateSearchResults(for searchController: UISearchController) {
      self.tableView.reloadData()

      self.filteredRecipeArray.removeAll(keepingCapacity: false)
      let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)

      let array = (self.filteredRecipeArray as NSArray).filtered(using: searchPredicate)

      self.filteredRecipeArray = array as! [foodRecipe]

      self.tableView.reloadData()
  }


  override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

      print("DidSelect index Path: \(indexPath.row)")
      //print("Filtered Manager Index: \(filteredmanagerArray[indexPath.row]))")

      self.performSegue(withIdentifier: "showDetail", sender: self)

  }

  // MARK: - Navigation

  // In a storyboard-based application, you will often want to do a little preparation before navigation
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

      if segue.identifier == "showDetail" {

          let index = self.tableView.indexPathForSelectedRow! as IndexPath

          let nav = segue.destination as! UINavigationController

          let vc = nav.viewControllers[0] as! DetailViewController

          if searchController.isActive {

              print("Manager Array Index: \(managerArray[index.row])")

              //var currentFilteredIndex = filteredmanagerArray[(indexPath as NSIndexPath).row]
              print("Filtered Manager Array Index: \(filteredmanagerArray[index.row])" 
          }
          else{
              vc.selectedmanagerArray = [managerArray[index.row]]

          }

          //vc.titleText = self.array.object(at: (index as NSIndexPath).row) as! String
          self.tableView.deselectRow(at: index, animated: true)

      }

  }

  // MARK: - UISplitViewControllerDelegate

  func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {

      return true

  }
}

Manager.swift

class Manager: NSObject{

    var id: String = String()
    var title: String = String()
    var ManagerDesignation: String = String()

}

谢谢。

再见。

最佳答案

我们可以只使用 Swift 内置的 filter 方法吗?

func updateSearchResults(for searchController: UISearchController) {
  self.tableView.reloadData()

  self.filteredRecipeArray.removeAll(keepingCapacity: false)
  guard let searchText = searchController.searchBar.text else {
      return
  }

  let array = managerArray.filter {
      return $0.id.range(of: searchText) != nil ||
             $0.title .range(of: searchText) != nil ||
             $0.ManagerDesignation.range(of: searchText) != nil
  }

  self.filteredRecipeArray = array

  self.tableView.reloadData()
}

编辑

更新了最新 Swift 3 语法的答案

关于ios - UISearchController更新搜索结果问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41270362/

相关文章:

objective-c - 在应用简历上显示登录 View

ios - Swift 无法在 MKAnnotation 中分配字幕

Swift 如何取消选择 Collection Cell

ios - 模式匹配和类型转换之间的区别

ios - 使用未解析的标识符 NSWorkspace

iOS 谷歌标签管理器集成 : How to add multiple containers per App environment?

ios - 如何将多张图片存储到 Parse 中的单个列?

ios - 更新到 Xamarin touch 8.2 并使用 mvvmcross

ios - 在这种情况下,数据对于类型查找是不明确的吗?

ios - 当我尝试从 Storyboard 中继续时,为什么我在这行代码中遇到段错误?