🖥️
iOS App with Pop
UIKit Swift 5
UIKit Swift 5
  • iOS App development
  • Swift
    • Variable & Constant
    • Number & String
    • Operator
    • Array, Dictionary & Tuple
    • Enum
    • Optional
    • Function
    • Class & Struct
    • Branching
    • Loops
    • Error handler
    • Protocol
    • Extension
  • Create New Project
  • Introduction to Xcode
  • Scene-Based Life-Cycle
  • UIViewController
  • Storyboard
  • First Run
  • Display todo list
  • Basic Auto Layout
  • MVC
  • Model
  • Binding TableView
  • Binding TableViewCell
  • TableViewDelegate
  • Add navigationBar with + button
  • Add new item page
  • TextField and Switch
  • Binding action
  • Add mock item to todo list
  • What is weak?
  • Finish add item
  • Delete todo item
  • Edit todo item
  • Custom new layout
  • Adding new delegate
  • Refactor
  • Pushing edit view
  • Large navigation
  • Drag item
  • Drop item (in app)
  • Save data
  • Where to go from here?
Powered by GitBook
On this page

TableViewDelegate

PreviousBinding TableViewCellNextAdd navigationBar with + button

Last updated 2 years ago

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

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

เมื่อเราเลือก item จะทำให้ cell นั้นมี state ค้างอยู่ในสถานะ selected เราจะต้องทำการ deselect ที่ cell นั้น

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

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

UITableViewDelegate

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

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

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

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

โค้ดสุดท้าย

ViewContrller.swift
import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    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
    }

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

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

เชื่อม Delegate