[英]SwiftUI - How to stop ScrollView receiving taps behind other view
[英]Move to other Picker View tabs only after the user taps on a button in an alert view - SwiftUI
我希望能夠做的是,當用戶點擊顏色選項卡時,首先在實際移動到另一個選項卡之前顯示一個警報視圖詢問,如果用戶決定Cancel
它不會移動到另一個選項卡但是如果用戶點擊OK
按鈕,Picker 將實際移動到選定的選項卡。
只有在用戶點擊警報視圖中的YES
按鈕后,我才能移動到不同的顏色選項卡?
struct ContentView: View {
@State private var favoriteColor = 0
@State private var showAlert = false
var body: some View {
VStack {
Picker("What is your favorite color?", selection: $favoriteColor) {
Text("Red").tag(0)
Text("Green").tag(1)
}
.pickerStyle(.segmented)
.onChange(of: favoriteColor) { tag in
showAlert = true
}
.alert("By changing color also modifieds other things...change color?", isPresented: $showAlert) {
Button("YES") {
// move to selected color tab
}
Button("Cancel") {
// do nothing
}
}
}
}
}
SwiftUI 是反應性世界,這意味着我們的代碼在事后接收控制...使用 UIKit 表示代替...
...或者,這是代理綁定的可能解決方法(但不確定行為是否在所有操作系統版本中都存在)
使用 Xcode 13.4 / iOS 15.5 測試
主要部分:
var selected: Binding<Int> { // << proxy !!
Binding<Int>(
get: { favoriteColor },
set: {
toConfirm = $0 // store for verification !!
showAlert = true // show alert !!
}
)
}
var body: some View {
VStack {
// << bind to proxy binding here !!
Picker("What is your favorite color?", selection: selected) {
Text("Red").tag(0)
Text("Green").tag(1)
}
.pickerStyle(.segmented)
.alert("By changing color also modifieds other things...change color?", isPresented: $showAlert, presenting: toConfirm) { color in // << inject for verification !!
Button("YES") {
favoriteColor = color // << do verification here !!
}
Button("Cancel") {
// do nothing
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.