I'm trying to capture the selected items from a UITableView and save them into a new array. The following code creates the new array by adding the items when the rows is tapped, what it doesn't do is remove the items when the rows are deselected.
How can I remove items from the newFruitList when a row in a UITableView is deselected?
Or better yet, what is the proper way to generate an array of only the selected items in a UITableView?
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let fruits = ["Apples", "Oranges", "Grapes", "Watermelon", "Peaches"]
var newFruitList:[String] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = fruits[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
newFruitList.append(fruits[indexPath.row])
print("New List: \(newFruitList)")
}
@IBAction func makeSelection(_ sender: Any) {
tableView.allowsMultipleSelectionDuringEditing = true
tableView.setEditing(true, animated: false)
}
}
