# Drop item (in app)

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

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

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

ประกาศ conform protocol

```swift
UITableViewDropDelegate
```

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

```swift
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 ฟังก์ชั่นนี้

```swift
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()
}
```

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

![](https://1168329629-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGk7Utff0rVWsqK4eYO%2F-LHNth1Dwm3AIcpzDC89%2F-LHNueMd8950ogA9HFn0%2FdragAndDrop.gif?alt=media\&token=7182b4ff-1394-4e05-a7ad-197259400de0)

{% hint style="info" %}
สามารถอ่านหัวข้อ Drag and Drop เพิ่มเติมได้ที่

[Supporting Drag and Drop in Table Views](https://developer.apple.com/documentation/uikit/views_and_controls/table_views/supporting_drag_and_drop_in_table_views)\
[Adopting Drag and Drop in a Table View](https://developer.apple.com/documentation/uikit/drag_and_drop/adopting_drag_and_drop_in_a_table_view)
{% endhint %}
