在类
class Objects {
var number: Int!
var name: String!
init(number: Int, name: String) {
self.number = number
self.name = name
}
}
在viewController
var allObjects = [Objects]()
var inSearchMode = false
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Cell
if inSearchMode {
let fill: Objects!
fill = filteredObject[indexPath.row]
cell.configureCell(fill)
} else {
let fill: Objects!
fill = allObjects[indexPath.row]
cell.configureCell(fill)
return cell
}
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if inSearchMode {
return filteredObject.count
}
return allObjects.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == nil || searchBar.text == "" {
inSearchMode = false
tableView.reloadData()
view.endEditing(true)
} else {
inSearchMode = true
var lowerCase = Int(searchBar.text!)
filteredObject = allObjects.filter({$0.number == lowerCase})
tableView.reloadData()
print(filteredObject)
}
}
我想要一个搜索栏,它可以过滤并仅显示一个包含我们要查找的号码的结果。我考虑过使用 contains
并将我们从搜索栏输入的数字放入其中。
我设法将一个对象放入 filteredObject
,但它不会显示在 tableView
中
最佳答案
仔细查看您的这部分代码:
if inSearchMode {
let fill: Objects!
fill = filteredObject[indexPath.row]
cell.configureCell(fill)
} else {
let fill: Objects!
fill = allObjects[indexPath.row]
cell.configureCell(fill)
return cell
}
您在搜索模式下没有返回单元格,这就是为什么您在搜索时看不到任何内容。
关于ios - 类数组中的过滤结果(Swift 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133331/