我使用数组和一个文本框创建了一个TableView。在文本框编辑时,根据文本框输入对TableView数据进行排序和筛选。如果TableView的数据是关于各州名称的,当我在文本框中输入‘A’时,所有以字母‘A’开头的州名将被排序并显示。请告诉我实现此功能的逻辑。
我使用数组和一个文本框创建了一个TableView。在文本框编辑时,根据文本框输入对TableView数据进行排序和筛选。如果TableView的数据是关于各州名称的,当我在文本框中输入‘A’时,所有以字母‘A’开头的州名将被排序并显示。请告诉我实现此功能的逻辑。
我的建议是使用UISearchController,它具有丰富的功能,如果你使用它,你现在所要求的非常简单。 所以请使用UISearchController。
UISearchController教程对你会很有帮助。
这个Youtube视频:https://www.youtube.com/watch?v=MgNRMcCWJhU&list=PLt2cCXacqzgfUAjHYnZ9rrPkih4NzAV4E&index=25
和网站链接可能会解决您的问题。
http://www.appcoda.com/custom-search-bar-tutorial/
您只需要不断重新加载表格并在编辑函数中放置代码。
例如:
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
shouldShowSearchResults = true
tblSearchResults.reloadData()
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchString = searchController.searchBar.text
// Filter the data array and get only those countries that match the search text.
filteredArray = dataArray.filter({ (country) -> Bool in
let countryText: NSString = country
return (countryText.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch).location) != NSNotFound
})
// Reload the tableview.
tblSearchResults.reloadData()
}