У меня есть табличное представление с двумя разделами, и я хочу, чтобы строки были переупорядочены только для одного из разделов. Я нашел много информации об этом, но не могу ограничить ее одним разделом. Вот весь мой код - это очень просто, с одним представлением таблицы. Я собрал это из разных источников - спасибо тем, кто внес свой вклад в это топи c.
Чтобы воспроизвести это в раскадровке, добавьте табличное представление к контроллеру представления, добавьте некоторые ограничения, установите число ячеек прототипа равным 1 и установите его идентификатор для «ячейки».
Таблица Представление состоит из двух разделов - «Фрукты» и «Цветы». Нажмите и удерживайте любую ячейку, чтобы переместить эту ячейку, поэтому эта часть работает нормально.
- Я хочу ограничить его, чтобы я мог перемещаться только в первом разделе.
- Кроме того, если я перетаскиваю ячейку и перемещаю ее из одного раздела в другой, он выдает ошибку и программа вылетает. Я бы хотел просто отклонить ход и вернуть ячейку в исходное положение.
Спасибо за любую помощь. Ян
import UIKit
import MobileCoreServices
var fruitList = ["Orange", "Banana", "Apple", "Blueberry", "Mango"]
var flowerList = ["Rose", "Dahlia", "Hydrangea"]
// this all works
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITableViewDragDelegate, UITableViewDropDelegate {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dragInteractionEnabled = true
tableView.dragDelegate = self
tableView.dropDelegate = self
tableView.dragInteractionEnabled = true
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Fruit"
} else {
return "Flowers"
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return fruitList.count
} else {
return flowerList.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
if indexPath.section == 0 {
cell.textLabel?.text = fruitList[indexPath.row]
} else {
cell.textLabel?.text = flowerList[indexPath.row]
}
return cell
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
var string: String
if indexPath.section == 0 {
string = fruitList[indexPath.row]
} else {
string = flowerList[indexPath.row]
}
guard let data = string.data(using: .utf8) else { return [] }
let itemProvider = NSItemProvider(item: data as NSData, typeIdentifier: kUTTypePlainText as String)
return [UIDragItem(itemProvider: itemProvider)]
}
func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
}
}