@jose
Чтобы реализовать свайповое удаление элемента в UITableView на языке Swift, можно воспользоваться методом делегата UITableView под названием tableView(_:trailingSwipeActionsConfigurationForRowAt:). Этот метод позволяет настроить действия при свайпе по ячейке таблицы, такие как удаление.
Ниже представлен пример, как это можно сделать:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import UIKit
class YourViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var items: [String] = ["Элемент 1", "Элемент 2", "Элемент 3", "Элемент 4"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
// MARK: - UITableViewDataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .destructive, title: "Удалить") { (action, view, completionHandler) in
// Удаляем элемент из массива данных
self.items.remove(at: indexPath.row)
// Обновляем таблицу
tableView.deleteRows(at: [indexPath], with: .automatic)
// Сообщаем системе, что действие выполнено
completionHandler(true)
}
let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
return configuration
}
}
|
Теперь, когда пользователь проводит пальцем влево по ячейке, он увидит кнопку для удаления элемента, и при нажатии на нее элемент будет удален как из представления, так и из структуры данных.