在SwiftUI中使用可观察对象切换视图

时间:2019-11-17 23:11:35

标签: swift navigation observable swiftui

我正在练习尝试使用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())
    }
}

1 个答案:

答案 0 :(得分:1)

您不需要此行即可使所有工作正常进行。只需注释掉这一行

//let objectWillChange = PassthroughSubject<ViewRouter, Never>()