SwiftUI-使用'ObservableObject'和@EnvironmentObject有条件地显示视图

时间:2019-08-14 04:49:48

标签: swift class struct observable swiftui

我想在应用程序中有条件地显示不同的视图-如果某个布尔值为true,则将显示一个视图。如果为假,将显示其他视图。此布尔值在ObservableObject类内,并且从将要显示的视图之一中更改。

PracticeStatus.swift(父视图)

import Foundation
import SwiftUI
import Combine

class PracticeStatus: ObservableObject  {
    @Published var showResults:Bool = false
}

PracticeView.swift(父视图)

struct PracticeView: View {
    @EnvironmentObject var practiceStatus: PracticeStatus

    var body: some View {
        VStack {
            if practiceStatus.showResults {
                ResultView()
            } else {
                QuestionView().environmentObject(PracticeStatus())
            }
        }
    }
}

QuestionView.swift

struct QuestionView: View {
    @EnvironmentObject var practiceStatus: PracticeStatus

    var body: some View {
        VStack {
            ...
            Button(action: {
                self.practiceStatus.showResults = true
            }) { ... }
            ...
        }
    }
}

但是,此代码无效。当按下QuestionView中的按钮时,不会显示ResultView。有人有解决方案吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您是否尝试过编译代码?有几个基本错误:

  1. 变量practicePracticeView中不存在。您是说practiceStatus吗?
  2. 变量userDataQuestionView中不存在。您是说practiceStatus吗?
  3. 您正在从PracticeView内部呼叫PracticeView!您肯定会得到堆栈溢出;-)您不是在说QuestionView吗?

以下是有效代码:

import Foundation
import SwiftUI
import Combine

class PracticeStatus: ObservableObject  {
    @Published var showResults:Bool = false
}

struct ContentView: View {
    @State private var flag = false

    var body: some View {
        PracticeView().environmentObject(PracticeStatus())
    }
}

struct PracticeView: View {
    @EnvironmentObject var practiceStatus: PracticeStatus

    var body: some View {
        VStack {
            if practiceStatus.showResults {
                ResultView()
            } else {
                QuestionView()
            }
        }
    }
}

struct QuestionView: View {
    @EnvironmentObject var practiceStatus: PracticeStatus

    var body: some View {
        VStack {

            Button(action: {
                self.practiceStatus.showResults = true
            }) {
                Text("button")
            }
        }
    }
}

struct ResultView: View {
    @State private var flag = false

    var body: some View {
        Text("RESULTS")
    }
}