iOS 8中的搜索功能

时间:2015-07-13 19:38:04

标签: ios swift uisearchbar

http://www.ioscreator.com/tutorials/add-search-table-view-tutorial-ios8-swift

我正在学习本教程。我使用Named Tuple得到了很多红色错误,而不是简单的数组,因为它在教程中。我需要一个元组,那么有人能为我的问题提供正确的代码吗?

我有这段代码:

var myData = [Data]()

// Adding data to the array
var newData = Data(category: "Lorem", name: "Ipsum")
myData.append(newData)

我在这里得到第一个错误:

controller.searchResultsUpdater = self

任何帮助?

1 个答案:

答案 0 :(得分:1)

我的解决方案。您应该添加UISearchResultsUpdatingUISearchControllerDelegateUISearchBarDelegate

var dataForSearch: [Music]? = nil
var searchController: UISearchController!
var searchPredicate: NSPredicate!

 func updateSearchResultsForSearchController(searchController: UISearchController) {
    self.dataForSearch?.removeAll(keepCapacity: false)
    var searchText = searchController.searchBar.text
    if searchController.active == true {
        searchPredicate = NSPredicate(format: "nameSong contains[c] %@", searchText)
        dataForSearch = self.fetchedResultsController?.fetchedObjects?.filter() {
           return self.searchPredicate.evaluateWithObject($0)
        } as! [Music]?
    }
    self.tableView.reloadData()
}

func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
    updateSearchResultsForSearchController(searchController)
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.delegate = self
    searchController = ({
        var controllerSearch = UISearchController(searchResultsController: nil)
        controllerSearch.delegate = self
        controllerSearch.searchBar.delegate = self
        controllerSearch.definesPresentationContext = false // default false
        controllerSearch.hidesNavigationBarDuringPresentation = true
        controllerSearch.searchBar.sizeToFit()
        controllerSearch.searchResultsUpdater = self 
        self.tableView.tableHeaderView = controllerSearch.searchBar
        return controllerSearch
    })()
    self.tableView.reloadData()
}