- 이번에는 SwiftUI에서 Alert 창을 띄우는 방법에 대해 알아보겠습니다.
Alert 창의 현재
- 과거의 Alert 창은 deprecated 되었습니다.
- 대신, View 프로토콜의 modifier인
alert(...)
을 사용해서 alert 창을 띄울 수 있습니다. - 이렇게 iOS 15부터는
alert
modifier로 Alert이 대체되었습니다.
struct ContentView: View {
@State private var showing = false
var body: some View {
Button("Alert 띄우기") {
showing = true
}
.alert("메시지", isPresented: $showing) {
Button("OK", role: .cancel) { ... }
}
}
}
여러개의 버튼 추가
role: .destructive
: 빨간색 강조 버튼role: .cancel
: 기본 취소 버튼
.alert("옵션 선택", isPresented: $showAlert) {
Button("삭제", role: .destructive) {
print("삭제 선택")
}
Button("취소", role: .cancel) { }
} message: {
Text("정말 삭제하시겠습니까?")
}
데이터 기반
- 특정 데이터가 있을 때만 Alert을 표시하려면 Identifiable을 활용할 수도 있습니다.
struct AlertData: Identifiable {
let id = UUID()
let title: String
let message: String
}
struct ContentView: View {
@State private var alertData: AlertData?
var body: some View {
Button("데이터 기반 알럿") {
alertData = AlertData(title: "오류", message: "네트워크 오류가 발생했습니다.")
}
.alert(alertData?.title ?? "", isPresented: $alertData) {
Button("확인", role: .cancel) { }
} message: {
Text(alertData?.message ?? "")
}
}
}
Alert 창의 과거
- Alert은 다음과 같은 파라미터를 갖고 있었습니다.
Alert(title: Text, message: Text?, dismissButton: Alert.Button?)
- 다음 코드와 같이 버튼과 @State 변수를 만들어, 버튼을 누르면 원하는 Alert 창이 나오게 할 수 있었습니다.
- 그리고 iOS 13과 14를 지원하기 위해서는 여전히 Alert을 이렇게 구현해야 합니다.
struct ContentViewNine: View {
@State private var showingAlert = false
var body: some View {
Button(action: {
self.showingAlert = true
}) {
Text("Show Alert")
}
.alert(isPresented: $showingAlert) {
Alert(title: Text("Title"), message: Text("This is a alert message"), dismissButton: .default(Text("Dismiss")))
}
}
}
마무리
- 이렇게 해서 SwiftUI에서는 Alert을 어떻게 띄우는지 알아봤습니다.