Skip to content

Instantly share code, notes, and snippets.

@skagedal
Created July 8, 2019 13:54
Show Gist options
  • Save skagedal/83db6a5c7903cfd1acb8799250afb520 to your computer and use it in GitHub Desktop.
Save skagedal/83db6a5c7903cfd1acb8799250afb520 to your computer and use it in GitHub Desktop.
// Demonstrating a bug with what the table view reports as the destination index path when dragging within
// the same section
import UIKit
class TableViewController: UITableViewController, UITableViewDragDelegate, UITableViewDropDelegate {
var data: [(String, [String])] = [("One", ["A", "B", "C"]), ("Two", ["1", "2", "3"])]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.dragInteractionEnabled = true
tableView.dragDelegate = self
tableView.dropDelegate = self
}
override func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].1.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
cell.textLabel?.text = data[indexPath.section].1[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return data[section].0
}
// DRAG
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
return [UIDragItem(itemProvider: NSItemProvider(object: DragItem(data[indexPath.section].1[indexPath.row])))]
}
// DROP
func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
guard let indexPath = destinationIndexPath else {
info("Forbidden")
return UITableViewDropProposal(operation: .forbidden)
}
// When reordering within the same section, unexpected results are shown here.
info("Insert at \(indexPath)?")
return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}
func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
guard let indexPath = coordinator.destinationIndexPath else {
info("Nowhere to drop")
return
}
info("Dropping at \(indexPath)")
}
func info(_ string: String) {
navigationItem.title = string
}
}
class DragItem: NSObject, NSItemProviderWriting {
static var writableTypeIdentifiersForItemProvider: [String] = ["tech.skagedal.test"]
func loadData(withTypeIdentifier typeIdentifier: String, forItemProviderCompletionHandler completionHandler: @escaping (Data?, Error?) -> Void) -> Progress? {
return nil
}
let string: String
init(_ string: String) {
self.string = string
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment