> For the complete documentation index, see [llms.txt](https://pakornpat.gitbook.io/ios-app/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pakornpat.gitbook.io/ios-app/drop-item-in-app.md).

# Drop item (in app)

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

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

```swift
override func viewDidLoad() {
    super.viewDidLoad()
    todo.add(item: TodoItem(title: "Download XCode", isDone: true))
    todo.add(item: TodoItem(title: "Buy milk"))
    todo.add(item: TodoItem(title: "Learning Swift", isDone: false))
    
    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 {
    session.localDragSession != nil
}

func tableView(_ tableView: UITableView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UITableViewDropProposal {
    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 {
    true
}

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

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

![](https://759097476-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FuqWEUpYllBlpWTYMEIgR%2Fuploads%2FI6dCr6lR1iXuhKr3QBFb%2FJun-28-2022%204-28-51%20PM.gif?alt=media\&token=af4bb2c5-9a8e-4b7f-bbf1-82c898e738f8)

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