首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UITableViewCell 點擊事件完整實作指南

     編輯:程式設計綜合問答

核心步驟

  1. 讓 Controller 符合 UITableViewDelegate 協定。
  2. 設定 tableView.delegate = self 與 tableView.dataSource = self。
  3. 實作 tableView(_:didSelectRowAt:) 代理方法。

程式碼範例 (Swift)

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
    }

    // MARK: - UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = "Row \(indexPath.row)"
        return cell
    }

    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true) // 取消灰色選中狀態
        print("使用者點擊了第 \(indexPath.section) 區第 \(indexPath.row) 列")
        // 依據 indexPath 執行對應業務邏輯
        if indexPath.section == 0, indexPath.row == 0 { /* 特定處理 */ }
    }
}

進階:自訂 Cell 加入手勢辨識器

若需在 Cell 內部特定區域(如按鈕、圖片)觸發動作,可在 awakeFromNib 或 init 加入 UITapGestureRecognizer:

let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
contentView.addGestureRecognizer(tap)
// 或針對子視圖
iconImageView.isUserInteractionEnabled = true
iconImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(iconTapped)))

注意:Cell 複用機制會導致手勢重複疊加,建議在 prepareForReuse 移除舊手勢或使用 tag 區分。

常見坑點

  • 忘記設定 delegate 導致方法不被呼叫。
  • 未呼叫 deselectRow 讓選中高亮常駐。
  • 在 didSelectRowAt 內直接 pushViewController 但未隱藏導航列返回鍵造成邏輯混亂。

遵循「代理模式 + 索引路徑判斷」是最標準、可維護的做法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved