본문 바로가기
Language/Swift

SwiftUI에서 사용하는 알림 메시지 (Alert)

by IFLA 2022. 10. 31.

사용자가 앱 또는 시스템의 상태에 응답하도록 경고를 사용한다.

 

기본코드

@State private var showAlert = false
var body: some View {
    Button("Show Alert") {
        showAlert = true
    }
    .alert(isPresented: $showAlert) {
        Alert(
            title: Text("Show Alert!"),
            message: Text("Hi, It's Alert")
        )
    }
}

 

실행 결과

 

 

사용 조건

  1. Alert를 표시할 지에 대한 여부를 지정하는 Bool 변수 (showAlert)
  2. Alert를 반환하는 클로저

 

SwiftUI는 bool 값이 상태이기 때문에 변경될 때마다 뷰를 새로 고친다. 결과적으로 true로 설정된 경우 알림창(Alert)가 표시됩니다. Alert가 해제되면 showAlert값도 자동으로 false로 설정된다.

 

응용 코드

@State private var showAlert = false
var body: some View {
    Button("Delete Alert") {
        showAlert = true
    }
    .alert(isPresented: $showAlert) {
        Alert(
            title: Text("Delete Alert!"),
            message: Text("Do you want to delete this content?"),
            primaryButton: .default(
                Text("Try Again"),
                action: {}
            ),
            secondaryButton: .destructive(
                Text("Delete"),
                action: {}
            )
        )
    }
}

 

실행 결과

 

기본코드에서 표시된 알림창은 경고용으로 사용되는 경우가 많다. 할일 앱에서 목록의 요소를 1개 삭제처리하면 알림창이 뜨지만 삭제할지 아니면 취소할 건지 선택해야하는 경우가 있다. 그럴 때 primaryButton과 sencodaryButton을 추가한다.

 

개발자 Document

Apple Developer Documentation

댓글


\