Reputation: 25
In my code I have a table view that loads the name of users using my app. When a user selects a row it will appear a checkmark. What I want to do is save an array that contains all the selected rows (the array will contain the names). I found some information, but I still learning iOS programming and I dont know Obj-c.
This is what I have done so far:
var selectedMembers = [String]?
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.names?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserCell") as! UITableViewCell
cell.textLabel!.text = names![indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
selectedMembers = Array()
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.accessoryType == .Checkmark
{
cell.accessoryType = .None
self.selectedMembers?.remove(indexPath)
}
else
{
cell.accessoryType = .Checkmark
self.selectedMembers?.append(indexPath)
}
}
}
Upvotes: 1
Views: 3884
Reputation: 1696
You can use the didSelectRowAtIndexPath and didDeselectRowAtIndexPath delegate methods like so to keep track of the index paths in the table.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedIndexPaths.append(indexPath)
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
if let index = find(selectedIndexPaths, indexPath) {
selectedIndexPaths.removeAtIndex(index)
}
}
Then you can backtrack and get the selected objects using the index paths.
Upvotes: 0
Reputation: 5083
To get the names you will need to use the selected row and get the entry of that row into your array with names.
To get the row of a indexpath
you can use
indexPath.row
To get the name of your member you would use
names![indexPath.row-1]
Ofcourse you would save this to your array using
self.selectedMembers?.append(names![indexPath.row-1])
to remove the item you will need to add an extra step
self.selectedMembers?.removeAtIndex(selectedMembers.indexOf(names![indexPath.row-1]))
Upvotes: 2