아이폰 유저라면 익숙할 알럿. 보통 관련 내용이 화면 중간에 나오고 OK, Cancel 버튼 등이 존재한다.
유저에게 중요한 정보를 전달하거나 경고를 할 때 사용되는 팝업 창이다.
앱 사용중 사용자에게 알림을 날리고 즉각적인 반응이 요구될 때 유용하다.
- 앱에서 오류가 발생했을 때
- 데이터를 삭제하기 전 (정말 삭제하시겠습니까?)
- 중요 업데이트, 공지사항을 전달할 때 등
// Created by Toughie on 2023/04/29.
//
import SwiftUI
struct AlertPrac: View {
@State var showAlert: Bool = false
@State var alertType: MyAlerts?
// @State var alertTitle: String = ""
// @State var alertMessage: String = ""
@State var backgroundColor: Color = Color.yellow
//열거형을 활용해 알럿 관리 ⭐️
//여러 케이스에 맞게 다양한 알럿을 보낼 수 있다.
enum MyAlerts {
case sucess
case error
}
var body: some View {
ZStack {
backgroundColor.opacity(0.7).ignoresSafeArea()
VStack {
Button("BUTTON 1") {
alertType = .sucess
// alertTitle = "SUCCESS🥳"
// alertMessage = "CONGRATS!"
showAlert.toggle()
}
.padding(.vertical, 100)
Button("BUTTON 2") {
alertType = .error
// alertTitle = "ERROR🔥"
// alertMessage = "TRY AGAIN"
showAlert.toggle()
}
}
.alert(isPresented: $showAlert) {
// Alert(title: Text("Error!"))
getAlert()
}
}
}
func getAlert() -> Alert {
//switch - case를 활용해 Alert 생성
switch alertType {
case .sucess:
return Alert(title: Text("SUCCESS🥳"), message: Text("CONGRATS!"), dismissButton: .default(Text("OK")))
case .error:
return Alert(title: Text("ERROR🔥"), message: Text("TRY AGAIN"), dismissButton: .default(Text("OK")))
default:
return Alert(title: Text("?"), message: Text("?"), dismissButton: .default(Text("?")))
}
// Alert(title: Text(alertTitle), message: Text(alertMessage), dismissButton: .default(Text("OK")))
// Alert(
// title: Text("Title"),
// message: Text("describe error"),
// primaryButton: .destructive(Text("DELETE"), action: {
// backgroundColor = Color.red
// }),
// secondaryButton: .cancel())
}
}
알럿을 하드코딩으로 여러개 작성하기 보다는(타이틀, 메세지, 액션, 버튼구성 등),
열거형을 통해 알럿이 필요한 케이스를 나열하고
케이스에 맞게 알럿을 변경하면 유동적으로 다양한 알럿을 보낼 수 있다. * func getAlert()
다만 알럿은 버튼이 1~2개 밖에 없기에
다양한 선택지가 필요한 경우 화면 하단에서 올라오는 '액션시트'를 활용해야한다.
'SwiftUI > SwiftUI(Basic)' 카테고리의 다른 글
32. [SwiftUI] .contextMenu() 컨텍스트 메뉴, Label() (0) | 2023.04.29 |
---|---|
31. [SwiftUI] .actionSheet() 액션시트 (0) | 2023.04.29 |
29. [SwiftUI] List() 리스트뷰 (0) | 2023.04.27 |
28. [SwiftUI] NavigationView, NavigationLink (0) | 2023.04.27 |
27. [SwiftUI] Popover Views (sheet, transition, offset) .zIndex(), px/pt (0) | 2023.04.27 |