Binding TableViewCell

โชว์ชื่อรายการให้ถูกต้อง

เนื่องจากเราใช้ TableViewCell ที่เป็น Basic ใน Cell จะมี Label มาให้แล้ว 1 อัน นั่นคือที่เราเห็นคำว่า Title

เราสามารถแก้ให้แสดงข้อความจาก todo item ของเราได้โดยการ set text property ให้ Label โดยการแก้โค้ด tableView(_:cellForRowAt:) ให้เป็นแบบนี้

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

indexPath จะมี property row กับ section เพื่อใช้ในการระบุตำแหน่งของ Cell และใช้ในการหาข้อมูล

TableView สามารถมีได้หลาย section แต่โดย default จะกำหนดเป็น 1 section ตัวอย่าง TableView ที่มีหลาย section ดูได้จาก แอป contact รายชื่อผู้ติดต่อจะถูกแบ่งเป็น section ตามตัวอักษร A, B, C, ...

ลองรันใหม่ จะเห็นว่า Cell จะเปลี่ยนมาใช้ข้อความจาก todo item ได้ถูกต้อง

แสดง Checkmark ให้อันที่ทำแล้วด้วย

TableViewCell ของเราจะมี accessoryType ที่เป็น checkmark ให้เราใช้ด้วย

ลองเปลี่ยน tableView(_:cellForRowAt:) อีกรอบให้เป็นแบบนี้

ViewController.swift
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
}

แล้วเพิ่มรายการที่ทำเสร็จแล้วใน viewDidLoad()

ViewController.swift
todo.add(item: TodoItem(title: "Download XCode", isDone: true))

เสร็จแล้วรัน จะเห็นว่ามี Checkmark ขึ้นมากับอันที่เราตั้ง isDone เป็น true แล้ว

โค้ดสุดท้ายของเราจะเป็นแบบนี้

ViewController.swift
import UIKit

class ViewController: UIViewController, UITableViewDataSource {

    var todo = Todo()

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        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
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        todo.add(item: TodoItem(title: "Buy milk"))
        todo.add(item: TodoItem(title: "Learning Swift"))
        todo.add(item: TodoItem(title: "Download XCode", isDone: true))
    }
}

Last updated