개발
SwiftUI) 시스템 Alert 뛰우기 및 사용하면서 느낀점들?
소소ing
2022. 5. 12. 15:09
반응형
UIKit + StoryBoard 사용당시 UIAlertViewController를 사용했었으나 SwiftUI에서는 Alert를 사용해야 한다.
SwiftUI에서 Alert를 사용하는 방법은 다음과 같다.
아래 코드를 보면 @State 변수인 isShow 값이 true일때 Alert가 노출되는 것을 볼 수 있다.
UIAlertViewConroller와 다르게 Alert은 isPresented에 해당되는 값이 반드시 있어야 한다.
struct AlertView: View {
@State private var isShow = true
var title : Text? = nil
var message : Text? = nil
var btn1 : Text? = nil
var body: some View {
VStack {
}
.alert(isPresented: $isShow) {
let btn1 = Alert.Button.default(btn1!) {
}
return Alert(title: title!,
message: message!,
dismissButton: btn1)
}
}
}
하여 .alert만 단독으로 사용은 불가하며, Button, VStack 등과 같이 UI 요소에 연계되어 사용이 가능하다.
아래 코드는 버튼을 클릭하여 alert을 노출하는 코드이다.
struct AlertView: View {
@State private var isShow = false
var title : Text? = nil
var message : Text? = nil
var btn1 : Text? = nil
var body: some View {
Button("Show Alert") {
isShow = true
}
.alert(isPresented: $isShow) {
let btn1 = Alert.Button.default(btn1!) {
}
return Alert(title: title!,
message: message!,
dismissButton: btn1)
}
}
}
UIAlertViewController와 다르게 Alert의 경우 버튼이 없는 상태로 출력을 할 수가 없다.
아래 코드와 같이 button 등록을 하지 않아도 기본 OK 버튼이 노출되게 된다.
.alert(isPresented: $isShow) {
let btn1 = Alert.Button.default(btn1!) {
}
return Alert(title: title!,
message: message!)
}
그외 사용자가 팝업을 닫더라도 동일한 팝업을 노출하고 싶다면.... DispatchQueue.main.asyncAfter를 이용하면 된다.
이는 @State 변수의 상태 값이 false와 true가 동시에 변경될 경우 바로 반영이 되지 않기 때문(@State 변수 고려사항)에 일정 시간 지연을 주어야 화면이 갱신되기 때문이다.
struct AlertView: View {
@State private var isShow = true
var title : Text? = nil
var message : Text? = nil
var btn1 : Text? = nil
var body: some View {
VStack {
}
.alert(isPresented: $isShow) {
let btn1 = Alert.Button.default(btn1!) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
isShow = true
})
}
return Alert(title: title!,
message: message!,
dismissButton: btn1)
}
}
}
반응형