我想点击一个视图中的按钮,然后更改另一个视图上的文本。改变bool的按钮在LessonOne上,而我想在ContentView上显示的文本。
我第一课中的代码是:
import SwiftUI
import Combine
class LessonTwoButton: ObservableObject {
let didChange = PassthroughSubject <Void, Never >()
var ButtonIsTapped = false {didSet {didChange.send()}}
}
struct LessonOne: View {
@ObservedObject var ActivateNextLesson = LessonTwoButton ()
var body: some View {
VStack{
Button (action: {
self.ActivateNextLesson.ButtonIsTapped.toggle()
}
, label: {
Text("Activate the next lesson")
})
}
}
}
我的ContentView中的代码是:
import SwiftUI
import Combine
struct ContentView: View {
@ObservedObject var lessontwobutton = LessonTwoButton()
var body: some View {
NavigationView{
VStack{
Text("Hello, world!")
.padding()
if lessontwobutton.ButtonIsTapped{
Text ("The button has been pressed. Your lesson is unlocked")}
else{
Text("This lesson is locked")
}
NavigationLink (
destination: LessonOne(),
label: {
Text("Next view")
})
}
}
}
}
代码运行,但它就是不绑定……我上了LessonOne,点击按钮,回到ContentView,什么都没有改变。你能告诉我该怎么办吗?
您需要在两个视图中使用相同的LessonTwoButton
实例:
struct ContentView: View {
@ObservedObject var lessontwobutton = LessonTwoButton() // create in parent only
...
struct LessonOne: View {
@ObservedObject var ActivateNextLesson: LessonTwoButton // declare only
...
}
NavigationLink(
destination: LessonOne(ActivateNextLesson: lessontwobutton), // pass here
label: {
Text("Next view")
}
)
LessonTwoButton
可以简化为
class LessonTwoButton: ObservableObject {
@Published var ButtonIsTapped = false
}