过滤类数组中的结果(Swift 3)
Posted
技术标签:
【中文标题】过滤类数组中的结果(Swift 3)【英文标题】:Filter result(s) in array of class (Swift 3) 【发布时间】:2016-12-14 01:26:35 【问题描述】:在Class
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
中
【问题讨论】:
【参考方案1】:仔细查看这部分代码:
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 nil 而不是什么都不做来表明我什么都不返回【参考方案2】:我会使用计算属性来驱动 tableview;此属性是所有对象或过滤后的对象:
var allObjects = [Objects]()
var filteredObjects: [Objects]?
var objects: [Objects] =
return filteredObjects ?? allObjects
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return self.objects.count
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Cell
let fill = self.objects[indexPath.row]
cell.configureCell(fill)
return cell
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
if searchBar.text == nil || searchBar.text == ""
self.filteredObjects = nil
else
var lowerCase = Int(searchBar.text!)
self.filteredObjects = allObjects.filter($0.number == lowerCase)
tableView.reloadData()
【讨论】:
以上是关于过滤类数组中的结果(Swift 3)的主要内容,如果未能解决你的问题,请参考以下文章