Как перетащить строки табличного представления в Swift, но только в одном разделе - PullRequest
0 голосов
/ 23 марта 2020

У меня есть табличное представление с двумя разделами, и я хочу, чтобы строки были переупорядочены только для одного из разделов. Я нашел много информации об этом, но не могу ограничить ее одним разделом. Вот весь мой код - это очень просто, с одним представлением таблицы. Я собрал это из разных источников - спасибо тем, кто внес свой вклад в это топи c.

Чтобы воспроизвести это в раскадровке, добавьте табличное представление к контроллеру представления, добавьте некоторые ограничения, установите число ячеек прототипа равным 1 и установите его идентификатор для «ячейки».

Таблица Представление состоит из двух разделов - «Фрукты» и «Цветы». Нажмите и удерживайте любую ячейку, чтобы переместить эту ячейку, поэтому эта часть работает нормально.

  1. Я хочу ограничить его, чтобы я мог перемещаться только в первом разделе.
  2. Кроме того, если я перетаскиваю ячейку и перемещаю ее из одного раздела в другой, он выдает ошибку и программа вылетает. Я бы хотел просто отклонить ход и вернуть ячейку в исходное положение.

Спасибо за любую помощь. Ян

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) {
  }

}

1 Ответ

0 голосов
/ 24 марта 2020

На тот случай, если кто-нибудь найдет здесь дорогу, благодаря ссылке, предоставленной @ Paulw11, это дополнительный бит кода, необходимый. Замените

  func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
  }

на

  func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let string = fruitList[sourceIndexPath.row]
    fruitList.remove(at: sourceIndexPath.row)
    fruitList.insert(string, at: destinationIndexPath.row)
  }

Очевидно, что это всего лишь простой пример программы, но я сейчас адаптировал этот код для сложной ситуации, и он отлично работает.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...