Drop item (in app)

แล้วก็ทำให้วางได้

คล้าย ๆ กับการทำให้ลากได้ ให้เราบอก TableView ว่า dropDelegate คือฉันนะ (TodoListViewController)

override func viewDidLoad() {
    super.viewDidLoad()
    loadTodo()
    tableView?.dragDelegate = self
    tableView?.dragInteractionEnabled = true
    
    tableView?.dropDelegate = self
}

ประกาศ conform protocol

UITableViewDropDelegate

เพิ่มฟังก์ชั่น UITableViewDropDelegate

func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {}

func tableView(_ tableView: UITableView, canHandle session: UIDropSession) -> Bool {
    return session.localDragSession != nil
}

func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
    return UITableViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath)
}

บรรทัดที่ 4 เป็นการบอกว่า drop จากเฉพาะ localDrag นะที่ทำได้ บรรทัดที่ 8 เป็นการระบุว่าเป็นการ move เพื่อให้หน้าจอแสดงไอคอน move

เนื่องจากเป็นการ reordering ทาง Apple บอกว่าจะไม่เรียกฟังก์ชั่น performDrop นะ ให้ใช้ TableViewDataSource อันเก่า

เราก็มาเพิ่ม UITableViewDataSource 2 ฟังก์ชั่นนี้

func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    todo.move(from: sourceIndexPath.row, to: destinationIndexPath.row)
    saveTodo()
}

เมื่อเรารันอีกทีคราวนี้เราก็จะลากวางได้ละ เป็นอันเสร็จ

สามารถอ่านหัวข้อ Drag and Drop เพิ่มเติมได้ที่

Supporting Drag and Drop in Table Views Adopting Drag and Drop in a Table View

Last updated