← 글 목록

notes

iOS - Storyboard Segue

iOS Storyboard Segue 화면 전환·데이터 전달과 연결 설정 메모.

처음 스토리보드에 Segue 화살표가 잔뜩 보이길래 “그냥 화면 연결선이겠지” 했다가, 데이터 넘길 때 prepare(for:sender:)에서 막혔다. 정리하면 Segue는 전환 트리거 + 목적지 VC 인스턴스 생성 묶음이다.

Segue가 하는 일

  • 소스 VC → 목적지 VC로 이동(push / modal / custom)
  • Storyboard Identifier로 코드에서도 performSegue(withIdentifier:sender:) 가능
  • 데이터는 보통 prepare(for segue: UIStoryboardSegue, sender: Any?)에서 꽂는다
flowchart LR
  A[소스 VC] -->|performSegue / 버튼 연결| S[Segue]
  S --> P[prepare for]
  P --> B[목적지 VC]

자주 쓰는 종류

데이터 넘기기

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toDetail",
       let dest = segue.destination as? DetailViewController {
        dest.itemId = sender as? String
    }
}

코드만으로 만들고 싶으면 Segue 없이:

let vc = storyboard?.instantiateViewController(withIdentifier: "DetailVC") as! DetailViewController
vc.itemId = id
navigationController?.pushViewController(vc, animated: true)

헷갈렸던 포인트

  • Identifier 안 달면 performSegue가 조용히 실패하는 것처럼 보임 → 스토리보드 Attributes에서 Identifier 확인
  • segue.destination이 NavigationController로 감싸져 있으면 .topViewController를 까야 함
  • SwiftUI로 넘어가면 Segue 개념 자체가 NavigationStack / sheet로 바뀜. 레거시 UIKit 프로젝트에서만 깊게 파면 됨