我有一些连续的拨动开关,但如果其中两个已经打开,我想防止开关打开。并显示一个警报,允许最多打开其中的 2 个。这是我的代码:
struct PreventToggle: View {
@State private var isCheckeds = [false, true, true, false, false, false]
@State var showAlert = false
var body: some View {
let numberOfTrue = isCheckeds.filter{$0}.count
showAlert = numberOfTrue > 2
return ForEach(0 ..< isCheckeds.count) { id in
Toggle("Switch \(id)", isOn: self.$isCheckeds[id])
.alert(isPresented: self.$showAlert) {
Alert(title: Text("Maximum Limit!"), message: Text("Maximum limit is: 3"), dismissButton: .default(Text("Got it")))
}
}
}
}
最佳答案
它是这样工作的:
struct PreventToggle: View {
@State private var isCheckeds = [false, true, true, false, false, false]
@State var lastSelected = -1
func alertBinding() -> Binding<Bool> {
Binding<Bool>(
get: {
let numberOfTrue = self.isCheckeds.filter{$0}.count
return numberOfTrue > 2 && self.lastSelected != -1
},
set: { _ in }
)
}
func toggleBinding(for index: Int) -> Binding<Bool> {
Binding<Bool>(
get: {
return self.isCheckeds[index]
},
set: { bool in
self.isCheckeds[index] = bool
self.lastSelected = index
}
)
}
var body: some View {
VStack {
ForEach(0 ..< isCheckeds.count) { id in
Toggle("Switch \(id)", isOn: self.toggleBinding(for: id))
}
}
.alert(isPresented: alertBinding()) {
Alert(title: Text("Maximum Limit!"),
message: Text("Maximum limit is: 3"),
dismissButton: .default(Text("Got it"), action: {
self.isCheckeds[self.lastSelected] = false
self.lastSelected = -1
})
)
}
}
}
关于ios - 防止切换开关打开并在 Swiftui 中显示警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61172203/