> 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/v1/tableviewdelegate.md).

# TableViewDelegate

## อย่าดูเหมือนค้างสิ

ถ้าเราลองรันดูตอนนี้ เมื่อลองกดเลือกที่แต่ละรายการ จะเห็นว่ามีไฮไลท์เกิดขึ้นเป็นสีเทา ๆ แต่ไม่หายไป

![](https://1168329629-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGk7Utff0rVWsqK4eYO%2F-LGtJfOil1Qzwl7EccDp%2F-LGtMG2mFdHL2YG3agm7%2Fselect2.gif?alt=media\&token=9510745e-f8a4-4411-b065-a665b03bb4ba)

วิธีการแก้คือ เราจะเพิ่มให้ ViewController เป็น Delegate ของ TableView และสั่งให้ TableView เลิก Select รายการนั้นหลังจาก Select เสร้จแล้ว เพื่อให้ไฮไลท์หายไป

ขั้นแรก เพิ่มที่หัว class ถัดจาก UITableViewDataSource

{% code title="" %}

```swift
UITableViewDelegate
```

{% endcode %}

แล้วเพิ่ม **tableView(\_:didSelectRowAt)**

```swift
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
}
```

จากนั้นเหมือนเดิมคือ เชื่อม TableView กับ ViewController ว่า ViewController เป็น delegate

![เชื่อม Delegate](https://1168329629-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGk7Utff0rVWsqK4eYO%2F-LGtJfOil1Qzwl7EccDp%2F-LGtLhg2mVE6rXGNwUrK%2Fdelegate.gif?alt=media\&token=7534289b-69d9-4d59-aa88-36571377c7a0)

รันใหม่และลองเลือกอีกครั้ง

![](https://1168329629-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGk7Utff0rVWsqK4eYO%2F-LGtJfOil1Qzwl7EccDp%2F-LGtMed8pVzl0Sz05IwF%2Fselect3.gif?alt=media\&token=4a581700-b0ea-4bc7-ac94-7d632c164264)

โค้ดสุดท้าย

{% code title="ViewContrller.swift" %}

```swift
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var todo = Todo()

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return todo.totalItems
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "todoItemCell", for: indexPath)
        let item = todo.item(at: indexPath.row)
        cell.textLabel?.text = item.title
        cell.accessoryType = item.isDone ? .checkmark : .none
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }

    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"))
    }
}
```

{% endcode %}
