[SwiftUI] 하나의 View에서 Alert을 여러 개 사용할 때 주의할 점.
SwiftUI
에서 Alert
을 사용하는 기본적인 방법은 다음과 같다.
@State public var isShow1: Bool = false
var body: some View {
VStack(spacing: 30.0) {
Button {
self.isShow1.toggle()
} label: {
Text("Alert 1")
}
.alert(isPresented: $isShow1) {
return Alert(title: Text("Alert1 show."))
}
}
.padding()
}
.alert()
은 예제 코드처럼 반드시 Button
에 할당해야 하는 건 아니고, View 요소에 padding()
달아주듯이 선언해주면 사용 가능하다.
매개변수 isPresented
에 바인딩시켜줄 @State
변수가 True로 변하는 순간 표시된다는 것만 잘 이해한다면 쉽게 사용 가능하다.
그러니, 아래처럼 하나의 View
내부에서 alert()
을 여러 개 선언하고 사용하는 것도 가능하다.
@State public var isShow1: Bool = false
@State public var isShow2: Bool = false
var body: some View {
VStack(spacing: 30.0) {
Button {
self.isShow1.toggle()
} label: {
Text("Alert 1")
}
.alert(isPresented: $isShow1) {
return Alert(title: Text("Alert1 show."))
}
Button {
self.isShow2.toggle()
} label: {
Text("Alert 2")
}
.alert(isPresented: $isShow2) {
return Alert(title: Text("Alert2 show."))
}
}
.padding()
}
그런데 Alert
을 여러 개 사용할 때 주의할 점은, 상위 View
에 alert을 선언하지 않도록 해야 한다는 점이다.
VStack(spacing: 30.0) {
Button {
self.isShow1.toggle()
} label: {
Text("Alert 1")
}
.alert(isPresented: $isShow1) {
return Alert(title: Text("Alert1 show."))
} // 상위 View에 존재하는 alert으로 인해, 동작하지 않음.
Button {
self.isShow2.toggle()
} label: {
Text("Alert 2")
}
// .alert(isPresented: $isShow2) { // 1. 여기 있던 alert()을
// return Alert(title: Text("Alert2 show."))
// }
}
.padding()
.alert(isPresented: $isShow2) { // 2. 이 쪽으로 옮김.
return Alert(title: Text("Alert2 show."))
}
위처럼 Button
을 감싸고 있는 VStack
에 alert
을 선언하면, VStack
안쪽의 첫 번째 버튼에 붙어있는 alert
은 동작하지 않게 된다.
다시 말해, alert
을 선언한 요소의 상위 View
에는 alert
을 선언하지 않도록 해야 한다는 것이다.
나만 몰랐지 또
'iOS(macOS) > SwiftUI' 카테고리의 다른 글
[SwiftUI/iOS] 이미지 파일로 Launch Screen 만들기 (0) | 2023.08.08 |
---|---|
[iOS/SwiftUI] Navigation - Back Button 커스텀 하기 (0) | 2023.04.26 |
[iOS/SwiftUI] ScrollView - 키보드 화면 가림 해결 예제 (0) | 2023.03.26 |
[SwiftUI] 경고 해결: Info.plist contained no UIScene configuration dictionary (looking for configuration named "(no name)") (0) | 2023.03.02 |
[SwiftUI/Xcode] Preview 화면 숨기기/나타내기 (0) | 2023.02.09 |