Alert 띄우기
아이폰에 Alert 띄우기
1. AlertController객체 생성
2. AlertAction 정의
3. 정의한 AlertAction을 Aler에 추가
4. Alert메서드 실행
Alert 객체 생성하기
Alert를 띄우기 위서는 먼저 AlertConroller 객체를 생성해야 합니다
생성자를 통해 타이틀, 내용, Alert타입을 선택할 수 있습니다
(❖그냥 AlertController()로 생성할 경우 actionSheet로 생성됩니다)
title과 messages는 프로퍼티이기 때문에 생성 이후에도 수정할 수 있습니다
preferredStyle은 actionSheet와 alert 두가지 타입이 있습니다
1. actionSheet
2. alert
Alert를 생성했다면 이제 위에 보이는 버튼(Action)을 정의할 차례입니다
Action 정의하기
액션객체를 생성해 줍니다
마지막 인자는 hander로 현재 액션이 선택되었을 때 동작해야할 로직을 정의합니다
let Action1 = UIAlertAction(title: "Action1", style: .destructive) { (action) in
//action
}
|
cs |
만약 아무 동작을 정의하고 싶지 않을 때엔 handler에 nil을 넣으면 되겠습니다
let Action1 = UIAlertAction(title: "Action1", style: .destructive, handler: nil)
|
cs |
style은 총 3가지의 타입이 존재합니다
cancel
default
destructive
default 와 cancel:
Alert에서는 굵기만 차이납니다
actionSheet는 버튼모양까지 차이가 납니다
destructive: 빨간색으로 표시됩니다
정의한 AlertAction Alert에 추가 및 띄우기
추가는 아래 메서드 하나로 쉽게 추가할 수 있습니다
alert.addAction(Action1)
Action1과 Action2 순서로 실행하면 아래와 같은 순서로 버튼이 생깁니다
Alert 띄우기
이제 Alert를 완벽하게 정의했으니 화면에 띄울 일만 남았습니다
present(alert, animated: false, completion: nil)
animated가 true이면 알림창이 부드럽게 뜨고 false면 애니메이션 없이 한번에 번쩍하고 나타납니다
completion에는 알림을 띄운 후 해야할 일들을 정의할 수 있습니다
present(alert, animated: true) {
//code
}
댓글