Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Push Segue từ UITableViewCell sang ViewController trong Swift

Tạo segue từ cell trong UITableViewController sang ViewController khác (Push navigation) rất đơn giản trên Storyboard.

Các bước trên Storyboard

  1. Xóa ViewController mặc định, thêm Table View Controller và View Controller mới.
  2. Chọn Prototype Cell trong Table View Controller, Attribute Inspector > Identifier: "cell".
  3. Ctrl-drag từ Prototype Cell sang View Controller thứ 2 > chọn Show (Push).
  4. Chọn Segue vừa tạo, Attribute Inspector > Identifier: "segueID" (để dùng trong code).
  5. Set Storyboard ID cho View Controller đích: "VC2".

Push Segue từ UITableViewCell sang ViewController trong Swift

Code TableViewController


class MyTableVC: UITableViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = "Row \(indexPath.row)"
        return cell
    }
    
    // Truyền data khi segue (optional)
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "segueID",
           let destination = segue.destination as? DetailViewController,
           let indexPath = tableView.indexPathForSelectedRow {
            
            destination.selectedRow = indexPath.row
            destination.itemTitle = "Row \(indexPath.row)"
        }
    }
}

Kết quả

Tap vào cell bất kỳ sẽ push sang ViewController chi tiết:

Push Segue từ UITableViewCell sang ViewController trong Swift

Lưu ý

  • Table View Controller phải nhúng trong Navigation Controller (Editor > Embed In > Navigation Controller) để Push hoạt động.
  • prepare(for:sender:) được gọi trước khi transition – nơi lý tưởng để truyền data.
  • Để disable selection cho một số cell: tableView.allowsSelection = false hoặc implement tableView(_:willSelectRowAt:).
  • iOS 13+: Có thể dùng UICollectionView + UICollectionViewCompositionalLayout cho layout phức tạp hơn.