我使用本教程创建了一个 UISearchBar 应用程序。一切正常,单元格配置正确,我可以按用户名搜索。
现在我正在尝试为每个单元格添加一个(复选标记✔︎),允许我(选择✔︎)列表中的多个用户。
该功能工作正常,但是当我搜索列表(选择✔︎)一个用户并返回到主表视图时,用户不会保持选中状态,反之亦然。
我如何(勾选✔︎)多个用户并在使用 UISearchBar 之前或之后维护该勾选标记?
class InviteViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate {
var allFriends = [Friend]()
var filteredFriends = [Friend]()
override func viewDidLoad() {
super.viewDidLoad()
###Call to get all Friends
getFriends()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.searchDisplayController!.searchResultsTableView {
return self.filteredFriends.count
} else {
return self.allFriends.count
}
}
var selectedFriendIndex:Int? = nil
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
var friend : Friend
if tableView == self.searchDisplayController!.searchResultsTableView {
friend = filteredFriends[indexPath.row]
} else {
friend = allFriends[indexPath.row]
}
###Configure the cell
cell.textLabel!.text = friend.username
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
if (indexPath.row == selectedFriendIndex) {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
} else {
cell.accessoryType = UITableViewCellAccessoryType.None
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
selectedFriendIndex = indexPath.row
let cell = tableView.cellForRowAtIndexPath(indexPath)
if let index = selectedFriendIndex {
if (cell?.accessoryType == .Checkmark) {
cell!.accessoryType = .None
} else {
cell!.accessoryType = .Checkmark
}
}
}
func filterContentForSearchText(searchText: String, scope: String = "All") {
self.filteredFriends = self.allFriends.filter({( friend : Friend) -> Bool in
var usernameMatch = (scope == "All") || (friend.username == scope)
var stringMatch = friend.username.lowercaseString.rangeOfString(searchText.lowercaseString)
return usernameMatch && (stringMatch != nil)
})
}
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool {
self.filterContentForSearchText(searchString)
return true
}
func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchScope searchOption: Int) -> Bool {
self.filterContentForSearchText(self.searchDisplayController!.searchBar.text)
return true
}
func searchDisplayController(controller: UISearchDisplayController, willHideSearchResultsTableView tableView: UITableView) {
self.tableView.reloadData()
}
}