Reputation:
I am trying to make a function that will append a selected row to an array and also remove from array when the row is deselected. Can you guys help me out with this?
Select Row Function:
var exercises = [exercise]() // Array that will be filled by selected rows
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath) as? exerciseCell
let exercisesSelected = selectedCell?.exerciseNameLbl.text
exercisenames.insert(exercisesSelected!, at: 0)
}
This is my deselect Delegate method:
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath) as? exerciseCell
if exercisenames.count < 1 {
print("empty array")
}else{
exercisenames.remove(at: indexPath.row)
print(exercisenames)
}
}
Looking forward for any help, thank you!
Kevin.
Upvotes: 1
Views: 1246
Reputation: 1239
You can use a for in
loop to remove a specific object in the array.
for (index,value) in exercisenames.enumerate() {
if value == selectedCell.exerciseNameLbl.text {
exercisenames.remove(at:index)
}
}
Upvotes: 2
Reputation: 1001
u can use only one delegate func for it, like this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if exercisenames.count < 1 {
print("empty array")
} else {
//check if exercise exist in array
if exercisenames.contain(/*your exercise*/) == true {
exercisenames.remove(at: indexPath.row)
tableView.deselectRow(at: indexPath, animated: true)
} else {
//insert to array
}
}
}
mb this helps u)
Upvotes: 0