1

创建代码后,我想创建一个摘要视图,允许我查看在选择器中选择的值。我能怎么做?我阅读了一些关于@ObservableObject 和@EnvironmentObject 的论坛,但我无法理解......非常感谢:)

import SwiftUI

//SUMMARYPAGE
struct SummaryView: View {
    var body: some View {
        NavigationView {
            Form {
                VStack(alignment: .leading, spacing: 6) {
                    Text("First Animal: \("firstAnimalSelected")")
                    Text("First Animal: \("secondAnimalSelected")")
                }
            }
        }
    }
}

struct SummaryView_Previews: PreviewProvider {
    static var previews: some View {
        SummaryView()
    }
}

enum Animal: String, CaseIterable {
    case select
    case bear
    case cat
    case dog
    case lion
    case tiger
}

struct ContentView: View {

    @State private var firstAnimal = Animal.allCases[0]
    @State private var secondAnimal = Animal.allCases[0]

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Animals")
                    .foregroundColor(.black)
                    .font(.system(size: 15))
                    .fontWeight(.bold)) {
                        Picker(selection: $firstAnimal, label: Text("Select first animal")) {
                            ForEach(Animal.allCases, id: \.self) { element in
                                Text(element.rawValue.capitalized)
                            }
                        }
                        Picker(selection: $secondAnimal, label: Text("Select second animal")) {
                            ForEach(Animal.allCases.filter { $0 != firstAnimal || firstAnimal == .select }, id: \.self) { element2 in
                                Text(element2.rawValue.capitalized)
                            }
                        }
                }.font(.system(size: 15))
            }.navigationBarTitle("List", displayMode: .inline)
        }
    }
}
4

1 回答 1

0

您可以将您的@State属性移动到ObservableObject

class ViewModel: ObservableObject {
    @Published var firstAnimal = Animal.allCases[0]
    @Published var secondAnimal = Animal.allCases[0]
}

并从以下位置访问它们@EnvironmentObject

struct ContentView: View {
    @EnvironmentObject var viewModel: ViewModel
    
    var body: some View {
        ...
        Picker(selection: $viewModel.firstAnimal, label: Text("Select first animal")) {
            ForEach(Animal.allCases, id: \.self) { element in
                Text(element.rawValue.capitalized)
            }
        }
    }
}
struct SummaryView: View {
    @EnvironmentObject var viewModel: ViewModel
    
    var body: some View {
        NavigationView {
            Form {
                VStack(alignment: .leading, spacing: 6) {
                    Text("First Animal: \(viewModel.firstAnimal.rawValue)")
                    Text("Second Animal: \(viewModel.secondAnimal.rawValue)")
                }
            }
        }
    }
}

请记住将您的注入ViewModel到您的根视图:

ContentView().environmentObject(ViewModel())
于 2020-07-22T19:35:03.650 回答