천원의 개발

iOS Alert 사용법 본문

iOS&Swift🍎/iOS

iOS Alert 사용법

천 원 2022. 7. 15. 18:24

 

 

https://developer.apple.com/documentation/uikit/uialertcontroller

 

Apple Developer Documentation

 

developer.apple.com

Alert 구현 단계
1. UIAlertController를 이용하여 Alert 생성
2. addAction를 이용해 생성한 Alert에 버튼 액션 추가
3. present를 이용해 Alert 표현

1. 단계

let alert = UIAlertController(title: "삭제", message: "정말 삭제 하겠습니까?", preferredStyle: .alert)

UIAlertController를 이용하여 Alert을 생성 해줍니다.

이때 preferredStyle이 .alert와 .actionSheet로 나뉘는데

 

Alert preferredStyle

• .alert : 팝업 창이 뜨는 느낌.
• .actionSheet : 아래에서 선택창이 올라오는 느낌.

2.단계 

let ok = UIAlertAction(title: "확인", style: .destructive, handler: nil)
let cancel = UIAlertAction(title: "취소버튼입니다.", style: .cancel, handler: nil)

handler안에는 각 버튼이 눌렸을 때의 이벤트를 설정 해줄 수 있습니다.

여기서도 style이 .default, .destructive, .cancel 형태로 나뉘는데

Alert addAction style

.default : 기본 형태
.destructive : 빨간 색으로 강조
.cancel : 취소 액션 (cancel타입을 두 개 이상 넣을시 런타임 에러가 발생하니 주의하자)

이제 생성한 action들을 Alert에 추가해주고

alert.addAction(ok)
alert.addAction(cancel)

3. 단계

present(alert, animated: true, completion: nil)

present를 통하여 화면에 보여주면

따란🎉

'iOS&Swift🍎 > iOS' 카테고리의 다른 글

iOS HTTP 통신 허용  (0) 2022.08.13
iOS 커스텀 폰트 사용법  (0) 2022.08.11
iOS Local Notification 사용법  (0) 2022.07.29
iOS UserDefaults 사용법  (0) 2022.07.17
iOS DateFormatter 사용법  (0) 2022.07.14