【发布时间】:2018-07-27 07:21:04
【问题描述】:
所以我有一个来自 API 的朋友列表,我也尝试实现搜索功能。到目前为止,一切都很好,过滤很好,但我的第一部分实际上是一个将我发送到另一个 VC 的按钮,当我尝试搜索朋友列表时,那个单元格总是出现,这让我很恼火。实际上,我希望在搜索朋友时将其隐藏。
可以看出第三张图清楚地显示了问题。
我的代码看起来像。
var friendList = [Conversations]()
var filteredFriends = [Conversations]()
func numberOfSections(in tableView: UITableView) -> Int {
return friendList.count + 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering() {
return filteredFriends.count
}
if section == 0 {
return 1
} else if section == 1 {
return friendList.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "NewGroupConversationCell") as! NewGroupConversationTableViewCell
return cell
} else if indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "NewConversationCell") as! NewConversationTableViewCell
var friendList: Conversations
if isFiltering() {
friendList = filteredFriends[indexPath.row]
} else {
friendList = self.friendList[indexPath.row]
}
cell.populate(friendList)
return cell
}
return UITableViewCell()
}
func searchBarIsEmpty() -> Bool {
// Returns true if the text is empty or nil
return searchController.searchBar.text?.isEmpty ?? true
}
func filterContentForSearchText(_ searchText: String, scope: String = "All") {
filteredFriends = friendList.filter({( friend : Conversations) -> Bool in
return (friend.name?.lowercased().contains(searchText.lowercased()))!
})
mainTableView.reloadData()
}
func isFiltering() -> Bool {
return searchController.isActive && !searchBarIsEmpty()
}
extension NewConversationViewController: UISearchResultsUpdating {
// MARK: - UISearchResultsUpdating Delegate
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
如果您需要更多解释,请告诉我。
【问题讨论】:
标签: ios swift uitableview swift3 uisearchbar