I am using a tableView to display data of users, I want to enable multiple user selection and for now it malfunctions in such that when I deselect a selected user, the user details still remains in the array which I am storing it inside. how can I fix this. below is my code currently
struct ChatUser {
var id: String
var name: String
}
var selectedUser: [ChatUser] = []
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if self.selectedUser.contains(self.users[indexPath.row]) {
let myIndex = self.selectedUser.index(of: self.users[indexPath.row])
self.selectedUser.remove(at: myIndex!)
} else {
self.selectedUser.append(self.users[indexPath.row])
}
selectedUser.forEach { (user) in
print("SELECTD \(user.id)")
}
}
答案 0 :(得分:2)
One thing to ensure here is that the struct is equatable
extension ChatUser: Equatable {
static func == (lhs: ChatUser, rhs: ChatUser) -> Bool {
return lhs.id == rhs.id
}
}
This is why your .contains
and .indexOf
are not working properly
答案 1 :(得分:2)
For removing your selected data for multi selection you can use didDeselectRowAt
method of tableview delegate.
struct ChatUser {
var id: String
var name: String
}
var selectedUser: [ChatUser] = []
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedUser.append(self.users[indexPath.row])
selectedUser.forEach { (user) in
print("SELECTD \(user.id)")
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if self.selectedUser.contains(self.users[indexPath.row]) {
let myIndex = self.selectedUser.index(of: self.users[indexPath.row])
self.selectedUser.remove(at: myIndex!)
}
}