gpt4 book ai didi

SwiftUI 绑定(bind) bool 外部 View - 'Accessing State' s 值不在 View 上安装'

转载 作者:行者123 更新时间:2023-12-04 15:18:00 25 4
gpt4 key购买 nike

我试图在一个简单的测验中将逻辑与我的 UI 分开,例如示例。但是当我完成这些问题时,我正在为如何离开而苦苦挣扎。
在 Xcode 12 中,我收到错误消息:

Accessing State's value outside of being installed on a View. Thiswill result in a constant Binding of the initial value and will notupdate.


我从其他答案中看到@State 只能在结构中使用,并建议发布。但是我似乎无法弄清楚如何使用带有绑定(bind)的已发布属性而不是“安装在 View 上”
class ViewModel: ObservableObject {
@Published var currentQuestion: String!

private var questions = ["one", "two", "three"]
private var index = 0

init() {
currentQuestion = questions[index]
}

func button(title: String) -> some View {
Button(action: { [self] in
if index < questions.count {
index += 1
currentQuestion = questions[index]
} else {
print("go to results view")
}
}) {
Text(title)
}
}
}

struct ContentView: View {
@ObservedObject var viewModel = ViewModel()

var body: some View {
NavigationView {
VStack {
viewModel.button(title: viewModel.currentQuestion)
}
}
}
}

struct ResultsView: View {
var body: some View {
Text("Results")
}
}
任何关于采取何种方法的建议将不胜感激!

最佳答案

您可以尝试在 ViewModel 中使用所有逻辑:

class ViewModel: ObservableObject {
@Published var currentQuestion: String!
@Published var showResults = false

private var questions = ["one", "two", "three"]
private var index = 0

init() {
currentQuestion = questions[index]
}

func nextQuestion() {
if index < questions.count {
index += 1
currentQuestion = questions[index]
} else {
showResults = true
}
}
}
和 View 中的 UI 组件(例如按钮):
struct ContentView: View {
@ObservedObject var viewModel = ViewModel()

var body: some View {
NavigationView {
VStack {
Text(viewModel.currentQuestion)
Button(action: viewModel.nextQuestion) {
Text("Next")
}
}
// if viewModel.showResults == true -> navigate to results
.background(NavigationLink(destination: ResultsView(), isActive: $viewModel.showResults) { EmptyView() } .hidden())
}
}
}
在上面的示例中,您转到 ResultsView使用 NavigationLink但您可以轻松地用结果替换当前 View 。演示由您决定。

关于SwiftUI 绑定(bind) bool 外部 View - 'Accessing State' s 值不在 View 上安装',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63978335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com