如何在IOS中在文本字段编辑时过滤表格视图数据

3

我使用数组和一个文本框创建了一个TableView。在文本框编辑时,根据文本框输入对TableView数据进行排序和筛选。如果TableView的数据是关于各州名称的,当我在文本框中输入‘A’时,所有以字母‘A’开头的州名将被排序并显示。请告诉我实现此功能的逻辑。


你可以使用Predicate来过滤结果,然后重新加载你的表格。 注意:保留两个数组,一个包含所有数据,另一个将保存从第一个数组中筛选出来的数据。希望这能帮到你。 - Janmenjaya
2个回答

0

我的建议是使用UISearchController,它具有丰富的功能,如果你使用它,你现在所要求的非常简单。 所以请使用UISearchController。

UISearchController教程对你会很有帮助。


0

这个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()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接