从SwiftUI中的模型确认



让我们想象一下,我有如下核心/模型:

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
}
}
}
}
}

归根结底,我想知道如何处理需要用户输入的处理程序,而我又无法理解

看起来你颠倒了交互性的概念,相反,你需要下面这样的东西(粗糙的(

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
}
...
}

最新更新