当我搜索商店时,餐桌会得到合适的商店。但是当我编辑我的搜索词(例如删除一个字母)时,该表变为空。即使我删除搜索词,表格也会变空!我必须转到另一个View Controller并返回搜索栏查看完整的表格。
这是我的代码
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
}
}
答案 0 :(得分:0)
在 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
}