This app shows a list of fruits. Swipe left on any fruit to see a red Delete button. Tapping Delete prints which fruit was deleted.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let tableView = UITableView()
var items = ["Apple", "Banana", "Cherry"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.frame = view.bounds
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = items[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let delete = UIContextualAction(style: .destructive, title: "Delete") { action, view, completion in
print("Deleted: \(self.items[indexPath.row])")
completion(true)
}
return UISwipeActionsConfiguration(actions: [delete])
}
}