UIKit에서 모달은 present(_:animated:completion:) 메서드를 통해
표시합니다.
let modalVC = UIViewController()
modalVC.view.backgroundColor = .white
present(modalVC, animated: true, completion: nil)
present(_:animated:completion:) : 현재 뷰 컨트롤러에서 새로운 뷰animated: true : 애니메이션 적용 여부completion : 표시가 끝난 후 실행할 코드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 정의모달은 dismiss(animated:completion:)으로 닫습니다.
self.dismiss(animated: true, completion: nil)
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)
}
}
modalTransitionStyle 속성으로 애니메이션 효과 변경 가능modalVC.modalTransitionStyle = .coverVertical // 아래서 위로 올라옴 (기본)
modalVC.modalTransitionStyle = .flipHorizontal // 좌우 반전
modalVC.modalTransitionStyle = .crossDissolve // 페이드 인/아웃
modalVC.modalTransitionStyle = .partialCurl // 페이지 말림 효과
present / dismiss 메서드로 제어modalPresentationStyle, modalTransitionStyle로 다양한 스타일.formSheet, .pageSheet 자주 활용