我正在练习使用SwiftUI中的可观察对象切换视图,但我的代码不起作用。我知道我可以用@State做到这一点,但我想用可观察的物体来实现这一点。当我点击内容视图中的图像时,图像不会改变。有人能帮我吗?
ContentView.swift
import SwiftUI
struct ContentView: View {
@ObservedObject var viewRouter: ViewRouter
var body: some View {
VStack {
Button(action: {self.viewRouter.currentPage = "Page2"}) {
Image(viewRouter.currentPage)
}
if viewRouter.currentPage == "Page1" {
Page1(viewRouter: viewRouter)
}else if viewRouter.currentPage == "Page2" {
Page2(viewRouter: viewRouter)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(viewRouter: ViewRouter())
}
}
ViewRouter.swift
import Foundation
import SwiftUI
import Combine
class ViewRouter: ObservableObject {
let objectWillChange = PassthroughSubject<ViewRouter, Never>()
@Published var currentPage: String = "Page1"
}
Page1.swift
import SwiftUI
struct Page1: View {
@ObservedObject var viewRouter:ViewRouter
var body: some View {
VStack {
Image("ET-LondonBridge")
}
}
}
struct Page1_Previews: PreviewProvider {
static var previews: some View {
Page1(viewRouter: ViewRouter())
}
}
Page2.swift
import SwiftUI
struct Page2: View {
@ObservedObject var viewRouter:ViewRouter
var body: some View {
VStack {
Image("BigBen")
.aspectRatio(contentMode: .fit)
}
}
}
struct Page2_Previews: PreviewProvider {
static var previews: some View {
Page2(viewRouter: ViewRouter())
}
}
您不需要这一行就可以使所有事情都正常工作。只需评论这行
//let objectWillChange = PassthroughSubject<ViewRouter, Never>()