TIL: Swift에서 Alert 사용하기 📱

jeongmuyamette·2025년 1월 6일

TIL

목록 보기
20/72
post-thumbnail

목차

  1. UIAlertController 기본 개념
  2. Alert Style 종류
  3. 기본 Alert 만들기
  4. Action Sheet 만들기
  5. Alert에 TextField 추가하기

1. UIAlertController 기본 개념

  • iOS에서 알림창을 표시하기 위해 사용하는 클래스
  • UIAlertController를 통해 Alert과 Action Sheet 두 가지 스타일 구현 가능
  • 주요 구성요소:
    • Title: 알림의 제목
    • Message: 부가 설명
    • Actions: 사용자가 선택할 수 있는 버튼들

2. Alert Style 종류

  1. Alert (.alert)
    • 화면 중앙에 표시
    • 중요한 정보나 사용자의 결정이 필요할 때 사용
  2. Action Sheet (.actionSheet)
    • 화면 하단에서 올라오는 형태
    • 여러 선택지를 제공할 때 사용

3. 기본 Alert 만들기

// 기본적인 Alert 생성
let alert = UIAlertController(
    title: "알림",
    message: "저장하시겠습니까?",
    preferredStyle: .alert
)

// 확인 버튼 추가
let okAction = UIAlertAction(
    title: "확인",
    style: .default
) { (action) in
    print("확인 버튼 탭")
}

// 취소 버튼 추가
let cancelAction = UIAlertAction(
    title: "취소",
    style: .cancel
)

// 액션들을 Alert에 추가
alert.addAction(okAction)
alert.addAction(cancelAction)

// Alert 표시
present(alert, animated: true)

4. Action Sheet 만들기

let actionSheet = UIAlertController(
    title: "선택해주세요",
    message: "원하는 작업을 선택하세요",
    preferredStyle: .actionSheet
)

let action1 = UIAlertAction(title: "사진 촬영", style: .default)
let action2 = UIAlertAction(title: "앨범에서 선택", style: .default)
let cancelAction = UIAlertAction(title: "취소", style: .cancel)

actionSheet.addAction(action1)
actionSheet.addAction(action2)
actionSheet.addAction(cancelAction)

present(actionSheet, animated: true)

5. Alert에 TextField 추가하기

let alert = UIAlertController(
    title: "로그인",
    message: "아이디와 비밀번호를 입력하세요",
    preferredStyle: .alert
)

// TextField 추가
alert.addTextField { (textField) in
    textField.placeholder = "아이디"
}
alert.addTextField { (textField) in
    textField.placeholder = "비밀번호"
    textField.isSecureTextEntry = true
}

let okAction = UIAlertAction(title: "확인", style: .default) { [weak alert] (_) in
    if let textFields = alert?.textFields {
        let username = textFields[0].text
        let password = textFields[1].text
        print("아이디: \(username ?? "")")
        print("비밀번호: \(password ?? "")")
    }
}

alert.addAction(okAction)
alert.addAction(UIAlertAction(title: "취소", style: .cancel))

present(alert, animated: true)

UIAlertAction Style 종류

  • .default: 기본 스타일
  • .cancel: 취소 동작을 나타내는 스타일
  • .destructive: 삭제와 같은 파괴적인 동작을 나타내는 빨간색 스타일

주의사항

  1. Alert는 메인 스레드에서 표시해야 함
  2. iPad에서 Action Sheet 사용 시 sourceView나 sourceRect 지정 필요
  3. 너무 많은 액션 버튼은 피하는 것이 좋음
  4. 간단명료한 메시지 사용 권장

활용 예시

// 간단한 확인 알림
func showSimpleAlert() {
    let alert = UIAlertController(
        title: "완료",
        message: "작업이 성공적으로 완료되었습니다.",
        preferredStyle: .alert
    )
    
    alert.addAction(UIAlertAction(title: "확인", style: .default))
    present(alert, animated: true)
}

// 삭제 확인 알림
func showDeleteAlert() {
    let alert = UIAlertController(
        title: "삭제 확인",
        message: "정말로 삭제하시겠습니까?",
        preferredStyle: .alert
    )
    
    alert.addAction(UIAlertAction(
        title: "삭제",
        style: .destructive
    ) { _ in
        // 삭제 로직 구현
    })
    
    alert.addAction(UIAlertAction(title: "취소", style: .cancel))
    present(alert, animated: true)
}

0개의 댓글