Swift UISearchBar未在TableView中查找信息

Swift UISearchBar未在TableView中查找信息,swift,uitableview,uisearchbar,Swift,Uitableview,Uisearchbar,我尝试从firebase获取数据,并在tableView中显示。一切都很好。但是我需要使用UISearchBar在tableView中搜索。我要解决两个问题 1)当我开始键入我的tableView时就会消失。不显示其中的所有信息 2)当我擦除UISearchBar中的所有内容时,不会显示任何内容 import UIKit import SPStorkController import Firebase class FoodViewController: UIViewController {

我尝试从
firebase
获取数据,并在
tableView
中显示。一切都很好。但是我需要使用
UISearchBar
在tableView中搜索。我要解决两个问题

1)当我开始键入我的
tableView
时就会消失。不显示其中的所有信息

2)当我擦除
UISearchBar
中的所有内容时,不会显示任何内容

import UIKit
import SPStorkController
import Firebase

class FoodViewController: UIViewController {

    override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }
    let tableView = UITableView()
    var foods = [FoodModel]()
    var searchedFoods = [String]()
    var searching = false

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchFoods()

        self.modalPresentationCapturesStatusBarAppearance = true
        self.view.backgroundColor = UIColor.white
        let controller = UIViewController()

        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")            

        self.view.addSubview(self.tableView)

        tableView.delegate = self
        tableView.dataSource = self

        let searchBar = UISearchBar(frame: CGRect(x: 0, y: 5, width: 350, height: 40))
        searchBar.searchBarStyle = .minimal
        searchBar.delegate = self

        self.view.addSubview(searchBar)            
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        self.updateLayout(with: self.view.frame.size)
    }

    func updateLayout(with size: CGSize) {
        self.tableView.frame = CGRect.init(x: 0, y: 45, width: size.width, height: 400)            
    }

    func fetchFoods() {
        Database.database().reference().child("food").observe(.childAdded) { (snapshot) in
            if let dict = snapshot.value as? [String: AnyObject] {
                let newTitle = dict["title"] as! String
                let exCell = FoodModel(title: newTitle)
                self.foods.append(exCell)
                DispatchQueue.main.async {
                    self.tableView.reloadData()                        
                }
            }                
        }            
    }
}

extension FoodViewController: UITableViewDataSource { 

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

        if searching {
            cell.textLabel?.text = searchedFoods[indexPath.row]
        } else {
            let food = foods[indexPath.item]
            cell.textLabel?.text = food.title
        }
        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searching {
            return searchedFoods.count
        } else {
            return foods.count
        }
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    }
}

extension FoodViewController: UITableViewDelegate {

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == self.tableView {
            SPStorkController.scrollViewDidScroll(scrollView)
        }
    }
}

extension FoodViewController: UISearchBarDelegate {

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        //searchedFoods = foods.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
        searching = true
        tableView.reloadData()
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searching = false
        searchBar.text = ""
        tableView.reloadData()
    }        
}`
这是我的模型

class FoodModel {

    var title = String()

    init (title: String) {

        self.title = title
    }
}

searchedFoods
应该是一个对象数组,与主食品列表相同

我想你只需要更新你的过滤

因此,将
searchedFoods
更改为
[FoodModel]()

然后将过滤器更改为:

searchedFoods = foods.filter({ $0.title.lowercased().prefix(searchText.count) == searchText.lowercased() })

searchedFoods
应该是一个对象数组,与主食品列表相同

我想你只需要更新你的过滤

因此,将
searchedFoods
更改为
[FoodModel]()

然后将过滤器更改为:

searchedFoods = foods.filter({ $0.title.lowercased().prefix(searchText.count) == searchText.lowercased() })

必须使用相同类型的数据源数组和筛选数组

var searchedfoods = [FoodModel]()
您必须实现
textdichange
,这样,如果搜索文本为空,它将取消搜索

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText.isEmpty {
        searchedFoods.removeAll()
        searching = false
    } else {
        searchedFoods = foods.filter{ $0.title.range(of: searchText, options: [.caseInsensitive, .anchored]) != nil }
        searching = true
    }
    tableView.reloadData()
}

你的API过滤的项目是非常繁琐和不必要的昂贵
range(of:options:
指定适当的选项效率更高。
不区分大小写
避免多次调用
小写()
。锚定
始终从字符串的开头开始搜索。

必须删除数据源数组和筛选数组的类型相同

var searchedfoods = [FoodModel]()
您必须实现
textdichange
,这样,如果搜索文本为空,它将取消搜索

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText.isEmpty {
        searchedFoods.removeAll()
        searching = false
    } else {
        searchedFoods = foods.filter{ $0.title.range(of: searchText, options: [.caseInsensitive, .anchored]) != nil }
        searching = true
    }
    tableView.reloadData()
}

用于筛选项目的API非常繁琐且不必要且昂贵。
范围(of:options:
指定适当的选项更有效。
不区分大小写
避免了多次调用
小写()
.archored
总是从字符串的开头开始搜索。

为什么searchedFoods是一个字符串数组?您不会将字符串分配给it@Scriptable我尝试使searchedFoods=[FoodModel](),但没有帮助。请告诉我如何重新设置您正在执行的筛选器将返回[FoodModel]@可编写脚本的,请编写一个代码。我不知道如何修复您已经有了代码:searchedFoods=foods.filter({$0.lowercased().prefix(searchText.count)==searchText.lowercased()})。将searchedFoods更改为[FoodModel](),然后再试一次为什么searchedFoods是字符串数组?您没有将字符串分配给it@Scriptable我尝试制作搜索食品=[FoodModel]()但它没有帮助。告诉我重新设置什么您正在执行的筛选器将返回[FoodModel]@Scriptable请编写一个代码。我不知道如何修复您已经有了代码:searchedFoods=foods.filter({$0.lowercased().prefix(searchText.count)=searchText.lowercased())。将searchedFoods更改为[FoodModel](),然后重试