このページでは、UITableViewのセルをタップした時に次のViewへ遷移させる方法について紹介します。
以前書いた記事「UITableViewの使い方」の続きですので、まだこちらを読んで無い方は先に読んでおいてください。
実装方法
セルをタップした時の処理は、以下のコードの「extension ViewController: UITableViewDelegate { }」の中に書いていきます。
import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    // 1.セルに表示するデータを準備
    var list = ["セル1", "セル2", "セル3", "セル4", "セル5"]
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}
// 2. テーブルビューの表示に関連する処理
extension ViewController: UITableViewDataSource {
    // 2-1. テーブルの行数を指定
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    // 2-2. セルに値をセット
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          // セルを取得        
        let cell = tableView.dequeueReusableCell(withIdentifier: "sampleCell", for: indexPath)        
        // セルに値をセット
        cell.textLabel?.text = list[indexPath.row]
        // セルを返却
        return cell
    }
}
// 3. セルをタップした時の処理など
extension ViewController: UITableViewDelegate {
}セルがタップされた時はfunc tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)が呼ばれるため、次のように書くことができます。
extension ViewController: UITableViewDelegate {
  // セルがタップされた時の処理
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 処理を記述
  }
}後は、「// 処理を記述」のところに画面遷移の処理を書くだけです。
なので次のように書けばいいですね。
extension ViewController: UITableViewDelegate {
  
// セルがタップされた時の処理
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "toGoNextView", sender: nil)
  }
} 画面遷移のやり方がさっぱりわからない場合は、以下の記事で詳しく説明しているので参考にしてください。
created by Rinker
							¥3,536
(2025/10/31 21:40:19時点 Amazon調べ-詳細)
(2025/10/31 21:40:19時点 Amazon調べ-詳細)



