[UIKit] UIAlertController & UIAlertAction

2024. 8. 23. 13:53·📱 iOS/UIKit

학습 목표

  • Alert 창을 띄워 사용자에게 알림을 줘보자

학습 내용

현재 뷰컨에서 Alert 띄우기 이론

현재 뷰컨트롤러에서 Alert 창을 띄우고 싶으면 다음 단계를 따라야 한다.

  1. UIAlertController 인스턴스 생성
  2. UIAlertAction 생성 후 1번 인스턴스에 addAction()으로 넣어줌
  3. 현재 뷰컨트롤러에서 self.present()로 1번 인스턴스를 띄워줌

Alert 띄우기 실습

resetButton을 눌렀을 때 동작하는 메소드이다.

@IBAction func resetButtonTapped(_ sender: Any) {
        // 이론의 1번 단계
    let alertController = UIAlertController(title: "게임 초기화", message: "모든 설정을 지우려고 합니다.\n다시 한 번 생각해보세요. 정말 지울까요?", preferredStyle: .alert)

    // 이론의 2번 단계
    let cancelAction = UIAlertAction(title: "Cancel", style: .default) { _ in
        print("Cancel 눌림")
    }
    let resetAction = UIAlertAction(title: "RESET", style: .destructive) { _ in
        print("RESET 눌림")
    }
    alertController.addAction(cancelAction)
    alertController.addAction(resetAction)

    // 이론의 3번 단계
    self.present(alertController, animated: true)
}

위 코드의 결과 사진

UIAlertController의 스타일

UIResponder - UIViewController - UIAlertController

actionSheet로 띄우기

  • 위와 같이 아래의 시트지가 나오게 된다.
  • 버튼은 addAction 순서대로 위에서 아래로 뜨게 된다.

alert로 띄우기

  • 위와 같은 모달 창이 뜸

UIAlertAction의 스타일

@MainActor open class UIAlertAction : NSObject, NSCopying {}

1. cancel

  • Alert 띄운 작업을 취소하지 않고, 변경하지 않겠음을 나타내는 스타일 적용
  • 파란색 + Bold 폰트로 적용됨
  • cancel로 등록된 Action을 나중에 넣었더라도, 왼쪽에 배치됨
      let cancelAction = UIAlertAction(title: "Cancel", style: .default) { _ in
          print("Cancel 눌림")
      }
      let resetAction = UIAlertAction(title: "RESET", style: .cancel) { _ in
          print("RESET 눌림")
      }
      alertController.addAction(cancelAction)
      alertController.addAction(resetAction)

2. default

  • 기본 스타일 작업 버튼 스타일 적용
  • 얇은 파란색 폰트

3. destructive

  • 해당 Alert가 데이터를 변경하거나 삭제할 수 있음을 나타내는 스타일 적용
  • 붉은색 + Bold 폰트가 적용됨
  • cancel과 달리 순서 상관 X

배운 점

  • UIAlertController과 UIAlertAction 관계에 대해 알게됨
  • UIAlertAction 메소드들을 이것저것 써보며 기능을 익힘

참조 링크

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

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

https://developer.apple.com/documentation/uikit/uialertaction/style

저작자표시 (새창열림)

'📱 iOS > UIKit' 카테고리의 다른 글

[UIView] frame & bounds (1)  (0) 2024.09.01
[UIKit] openURL vs SFSafariViewController, 앱 사용 중에 URL 페이지 띄워주는 방식의 차이 알아보기  (1) 2024.08.24
[UIKit] UIViewController LifeCycle (탭바와 함께)  (0) 2024.08.22
[UIKit] UIButton 타입과 메소드  (2) 2024.08.21
[UIKit] UISegmentedControl 사용해보기  (0) 2024.06.17
'📱 iOS/UIKit' 카테고리의 다른 글
  • [UIView] frame & bounds (1)
  • [UIKit] openURL vs SFSafariViewController, 앱 사용 중에 URL 페이지 띄워주는 방식의 차이 알아보기
  • [UIKit] UIViewController LifeCycle (탭바와 함께)
  • [UIKit] UIButton 타입과 메소드
kyxxn
kyxxn
컴퓨터공학을 좋아하는 대학생의 공부 일기
  • kyxxn
    컴공 학부생의 공부 일기
    kyxxn
  • 전체
    오늘
    어제
    • 분류 전체보기 (156)
      • 📱 iOS (64)
        • Xcode (10)
        • Swift (17)
        • Swift Concurrency (12)
        • UIKit (21)
        • SwiftUI (0)
      • 🖥️ Computer Science (57)
        • 🏛️ Software Architecture Pa.. (2)
        • 👨🏻‍🎨 Design Pattern (3)
        • Data Structure (4)
        • Algorithm (10)
        • Computer Architecture (4)
        • Operating System (19)
        • Network (15)
      • ✍🏻 회고록 (9)
      • 🎸 기타 (25)
        • 해커톤 (1)
        • git (6)
        • 세미나 (1)
        • 책을 읽고 (1)
        • AOS, Kotlin (6)
        • Reinforcement Learning (9)
  • 블로그 메뉴

    • 링크

      • 깃허브
      • 일상 블로그
    • 공지사항

    • 인기 글

    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    kyxxn
    [UIKit] UIAlertController & UIAlertAction
    상단으로

    티스토리툴바