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])
}
}
Are you sure you made any selection in tableView ?
To avoid crash, test for nil, with :
guard let index = top30QuarterbacksTable.indexPathForSelectedRow else { return } // Do not add player
// After this, continue with your code
But you should ease your life.
Change paramet in addPlayer to the full indexPath
alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { (alertAction) in
self.addPlayer(index: indexPath)
}))
Then, no need to look for selected.
It is still safer to test for nil:
func addPlayer(index: IndexPath) {
guard let cell = top30QuarterbacksTable.cellForRow(at: index) else { return } // Should never occur
let string = objectsArray[0]
cell.textLabel?.text = string
if myRoster!.isEmpty {
myRoster?.insert(string, at: 0)
} else {
myRoster?.append(string)
}
}