[TIL] 모달 구현

Eden·2025년 9월 1일
  • 모달창(Modal View Controller)은 기존 화면 위에 새로운 화면을
    덮어씌워 사용자에게 중요한 작업을 수행하도록 만드는 방식입니다.
  • 예: 로그인 화면, 설정 팝업 등.

UIKit에서 모달은 present(_:animated:completion:) 메서드를 통해
표시합니다.


2. 모달창 띄우는 기본 방법

let modalVC = UIViewController()
modalVC.view.backgroundColor = .white
present(modalVC, animated: true, completion: nil)
  • present(_:animated:completion:) : 현재 뷰 컨트롤러에서 새로운 뷰
    컨트롤러를 띄움
  • animated: true : 애니메이션 적용 여부
  • completion : 표시가 끝난 후 실행할 코드

3. 모달 스타일 설정

UIKit은 여러 가지 모달 스타일을 제공합니다.

let modalVC = UIViewController()
modalVC.modalPresentationStyle = .fullScreen // 전체 화면
present(modalVC, animated: true)

주요 스타일 종류

  • .automatic : 시스템이 상황에 맞게 자동 결정 (iOS 13 이상 기본)
  • .fullScreen : 전체 화면 덮기
  • .pageSheet : 페이지 시트 형태 (iPad, iPhone Large Display)
  • .formSheet : 작은 팝업 형태 (iPad)
  • .overFullScreen : 배경 보이면서 전체 화면
  • .custom : 개발자가 직접 transition 정의

4. 모달 닫기

모달은 dismiss(animated:completion:)으로 닫습니다.

self.dismiss(animated: true, completion: nil)

5. 실전 예제: 버튼 클릭 시 모달 띄우기

class MainViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemBackground

        let button = UIButton(type: .system)
        button.setTitle("모달 열기", for: .normal)
        button.addTarget(self, action: #selector(openModal), for: .touchUpInside)

        button.center = view.center
        button.frame.size = CGSize(width: 120, height: 50)
        view.addSubview(button)
    }

    @objc func openModal() {
        let modalVC = ModalViewController()
        modalVC.modalPresentationStyle = .pageSheet
        present(modalVC, animated: true)
    }
}

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemTeal

        let closeButton = UIButton(type: .system)
        closeButton.setTitle("닫기", for: .normal)
        closeButton.addTarget(self, action: #selector(close), for: .touchUpInside)

        closeButton.center = view.center
        closeButton.frame.size = CGSize(width: 100, height: 40)
        view.addSubview(closeButton)
    }

    @objc func close() {
        dismiss(animated: true, completion: nil)
    }
}

6. 모달 전환 애니메이션 커스터마이징

  • modalTransitionStyle 속성으로 애니메이션 효과 변경 가능
modalVC.modalTransitionStyle = .coverVertical  // 아래서 위로 올라옴 (기본)
modalVC.modalTransitionStyle = .flipHorizontal // 좌우 반전
modalVC.modalTransitionStyle = .crossDissolve  // 페이드 인/아웃
modalVC.modalTransitionStyle = .partialCurl    // 페이지 말림 효과

7. 정리

  • 모달창은 중요한 작업을 위해 기존 UI 위에 새로운 화면을 표시하는 방식
  • present / dismiss 메서드로 제어
  • modalPresentationStyle, modalTransitionStyle로 다양한 스타일
    적용 가능
  • iPad에서는 .formSheet, .pageSheet 자주 활용
profile
iOS Dev

0개의 댓글