ios - 类数组中的过滤结果(Swift 3)

标签 ios arrays swift uitableview

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/

相关文章:

ios - 使用 NSOperations 时关联 NSManagedObjectContexts

ios - 检测 UILabel 中的点击标签

ios - 如何像 ALAssetsLibrary 一样使用 PHPhotoLibrary

javascript - 将 javascript 数组转换为 Float32Array 到缓冲区并返回

swift - 子类的闭包/回调中的 instancetype 参数类型

ios - UITableView beginUpdates endUpdates 使行闪烁

c - "Invisible"操作二维数组时出错。 (0 个错误,0 个警告)

arrays - 如何向 powershell 对象添加新属性

swift - 带有泛型参数的复杂 Swift 闭包

swift - 不占全屏宽度时获取UILabel宽度?