การนำทางระหว่าง View Controller ใน iOS ใช้ Navigation Controller ซึ่งจัดการ Stack ของ View Controller
ขั้นตอนที่ 1: สร้าง View Controller Object
let vc = storyboard?.instantiateViewController(withIdentifier: "VC2ViewController") as! VC2ViewController
Identifier ต้องตรงกับ Storyboard ID ที่ตั้งไว้ใน Identity Inspector
ขั้นตอนที่ 2: นำทางไป View Controller อื่น
Push (ใช้กับ Navigation Controller)
navigationController?.pushViewController(vc, animated: true)
Present (Modal)
present(vc, animated: true, completion: nil)
โค้ดเต็มตัวอย่าง
class FirstViewController: UIViewController {
@IBAction func goToSecond(_ sender: UIButton) {
guard let vc = storyboard?.instantiateViewController(withIdentifier: "SecondVC") as? SecondViewController else { return }
// ส่งข้อมูลได้ที่นี่
vc.data = "Hello from First VC"
navigationController?.pushViewController(vc, animated: true)
// หรือ present(vc, animated: true)
}
}
Push vs Present
| คุณสมบัติ | Push | Present |
|---|---|---|
| ต้องการ Navigation Controller | ใช่ | ไม่จำเป็น |
| มี Back Button อัตโนมัติ | ใช่ | ไม่ (ต้องเพิ่มเอง) |
| เหมาะสำหรับ | Drill-down navigation | Modal, Form, Alert |
Unwind Segue (กลับไปหน้าก่อนหน้า)
@IBAction func unwindToFirst(segue: UIStoryboardSegue) {}
ใน Storyboard: Ctrl-drag จากปุ่มไปที่ Exit icon เลือก unwindToFirst