UISearchBar for Swift 3



如何在Swift 3中使用核心数据处理UISearchBar?我找到了一个 在Google上的教程,但许多事情在新版本的 Swift。

您必须首先获取使用Fetch函数保存的所有核心数据,然后您可以使用搜索栏委托使用过滤器函数来过滤结果。

do {
        let fetchReq: NSFetchRequest<NSFetchRequestResult> = YourEntityName.fetchRequest()

        let Array = try returnContext().fetch(fetchReq)
        for entity in Array {
            let Entity: Array = entity as! YourEntityName
                let filter = Entity.filter({ (item: ContactData) -> Bool in                     
                    //Use range(of:) function to filter your result with the searched result and return true or false accordingly.
                    let str = name.lowercased().range(of: searchText.lowercased())
                    return str != nil ? true : false
                })
                if filter.count > 0 {
                   //Use this block to create a temporary data model and then use tableView.reloadData() to reload your table with the searched results. This block is not necessary. Its usability depends on your source code.
                }
            }
        }
    } catch {
        print("ERROR")
    }

最新更新