I have a table view and an array of strings. When I swipe a row, I want to add the clicked string to an array of strings. How do I get the value stored in the table view row. I have it set up like this:
import UIKit
var myStringArray: [String]?
var someStringArray: [String] = ["Hot Dogs", "Soda", "Chips", "Hamburgers", "Plates", "Dessert", "Napkins", "Fruit",
"Potatoe Salad", "Brats"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return someStringArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)
cell.textLabel?.text = someStringArray[indexPath.row]
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.textLabel?.font = UIFont.systemFont(ofSize: 22)
return cell
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let object: String = someStringArray[indexPath.row]
let add = UIContextualAction(style: .normal, title: "Add") { (contextualAction, view, actionPerformed: @escaping (Bool) -> Void) in
let alert = UIAlertController(title: "Add ", message: "Are you sure you want to add '\(object)' to your list?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { (alertAction) in
actionPerformed(false)
}))
alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { (alertAction) in
self.addObject()
}))
self.present(alert, animated: true)
}
return UISwipeActionsConfiguration(actions: [add, taken])
}
func addObject(index: Int) {
let index = table.indexPathForSelectedRow
let _index = (index?[someStringArray.hashValue])!
if myStringArray!.isEmpty {
myStringArray?.insert(someStringArray[_index], at: 0)
} else {
myStringArray?.append(someStringArray[_index])
}
}