从SwiftUI中的模型确认
让我们想象一下,我有如下核心/模型:从SwiftUI中的模型确认,swiftui,Swiftui,让我们想象一下,我有如下核心/模型: class Core: ObservableObject { ... func action(confirm: () -> Bool) { if state == .needsConfirmation, !confirm() { return } changeState() } ... } 然后我在SwiftUI视图中使用这个核心对象 struct ListView: View { ...
class Core: ObservableObject {
...
func action(confirm: () -> Bool) {
if state == .needsConfirmation, !confirm() {
return
}
changeState()
}
...
}
然后我在SwiftUI视图中使用这个核心对象
struct ListView: View {
...
var body: some View {
List(objects) {
Text($0)
.onTapGesture {
core.action {
// present an alert to the user and return if the user confirms or not
}
}
}
}
}
因此,我想知道如何使用处理程序,因为需要用户的输入,而我无法对其进行思考。看起来你颠倒了交互概念,相反,你需要下面这样的东西(scratchy) 结构列表视图:视图{ @国家私有var confirmAlert=false ... var body:一些观点{ 列表(对象){ 文本(0美元) .ontapsigne{ 如果core.needs需要确认{ self.confirmAlert=true }否则{
self.core.action()//那么你的问题是如何显示警报?我不仅知道如何显示警报。而且在操作处理程序中,在
ListView
中,我需要显示警报,如果用户按下“OK”返回true或falseHey@Asperi,感谢您的回复。我希望不会出现这样的情况,self.core.action()需要在两个位置调用,这也是有问题的,因为core.needsConfirmation
实际上是一个网络调用。我希望Combine可能有解决类似问题的方法?
struct ListView: View {
@State private var confirmAlert = false
...
var body: some View {
List(objects) {
Text($0)
.onTapGesture {
if core.needsConfirmation {
self.confirmAlert = true
} else {
self.core.action() // << direct action
}
}
}
.alert(isPresented: $confirmAlert) {
Alert(title: Text("Title"), message: Text("Message"),
primaryButton: .default(Text("Confirm")) {
self.core.needsConfirmation = false
self.core.action() // <<< confirmed action
},
secondaryButton: .cancel())
}
}
}
class Core: ObservableObject {
var needsConfirmation = true
...
func action() {
// just act
}
...
}
struct ListView: View {
@ObservedObject core: Core
...
var body: some View {
List(objects) {
Text($0)
.onTapGesture {
self.core.action() // << direct action
}
}
.alert(isPresented: $core.needsConfirmation) {
Alert(title: Text("Title"), message: Text("Message"),
primaryButton: .default(Text("Confirm")) {
self.core.action(state: .confirmed) // <<< confirmed action
},
secondaryButton: .cancel())
}
}
}
class Core: ObservableObject {
@Published var needsConfirmation = false
...
func action(state: State = .check) {
if state == .check && self.state != .confirmed {
self.needsConfirmation = true
return;
}
self.state = state
// just act
}
...
}