所以我有一个来自 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!)
}
如果您需要更多解释,请告诉我。
您的 numberOfSection 等于朋友数,这就是为什么您的操作按钮数等于朋友数的原因,请尝试
func numberOfSections(in tableView: UITableView) -> Int {
return 2 // your button, and your friend list
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
if isFiltering() {
return 0 // hide button
}
return 1
} else if section == 1 {
if isFiltering() {
return filteredFriends.count
}
return friendList.count
}
return 0
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句