简体   繁体   English

如何将 SwiftUI 中的 static 值从一个视图传递到另一个视图?

[英]How to pass static values in SwiftUI from one View to another?

I'm new to learning SwiftUI and XCode and am unable to figure out how to pass a variable from view to another.我是学习 SwiftUI 和 XCode 的新手,无法弄清楚如何将变量从视图传递到另一个视图。 I read on @State and @Binding variables but from what I can tell that is for values that change.我阅读了@State 和@Binding 变量,但据我所知,这是针对变化的值。 I have a static value that I calculate based on the date when the user opens the app.我有一个 static 值,我根据用户打开应用程序的日期计算得出。

The variable is the current moon phase and is stored locally in my main ContentView.该变量是当前的月相,并本地存储在我的主 ContentView 中。 I want to pass this variable to a second view that's accessed by clicking a NavigationLink.我想将此变量传递给通过单击 NavigationLink 访问的第二个视图。

ContentView.swift ContentView.swift

import SwiftUI

struct ContentView: View {
    
    
    var body: some View {
        
        
        let currentMoonPhaseArray = calculateMoonPhase()
        let moonPhase = currentMoonPhaseArray[0]
        
        NavigationView{
            ScrollView(.vertical, showsIndicators:true) {
                VStack(spacing:3){
                    NavigationLink(destination: MoonPhaseView()){
                        Text("Moon Phase - " + moonPhase)
                    }
                }
            }
        .frame(maxWidth: .infinity)
        .navigationTitle("MySky")
        .navigationBarTitleDisplayMode(.inline)
        }
        
    }
}

MoonPhaseView.swift MoonPhaseView.swift

import SwiftUI

struct MoonPhaseView: View {
    
    
    var body: some View {
        HStack{
            Text("MoonPhaseView!")
        }
    }
}

struct MoonPhaseView_Previews: PreviewProvider {
    static var previews: some View {
        MoonPhaseView()
    }
}

My goal is to have the calculated moon phase from ContentView.swift be passed to the MoonPhaseView.swift.我的目标是将 ContentView.swift 计算的月相传递给 MoonPhaseView.swift。 I believe that bindings are the correct approach from what I've read, but all binding implementations seem to be for updating views often.我相信绑定是我读过的正确方法,但所有绑定实现似乎都是为了经常更新视图。

Thanks for any help or pointers!感谢您的任何帮助或指点!

You haven't shown what the type of moonPhase is, so I'm just going to use String as an example.你还没有展示moonPhase的类型是什么,所以我将使用String作为示例。


struct ContentView: View {
    
    func calculateMoonPhase() -> [String] {
        return ["Full","Waxing","Waning"]
    }
    
    var body: some View {
        let currentMoonPhaseArray = calculateMoonPhase()
        let moonPhase = currentMoonPhaseArray[0]
        
        NavigationView{
            ScrollView(.vertical, showsIndicators:true) {
                VStack(spacing:3){
                    NavigationLink(destination: MoonPhaseView(phase: moonPhase)){
                        Text("Moon Phase - " + moonPhase)
                    }
                }
            }
            .frame(maxWidth: .infinity)
            .navigationTitle("MySky")
            .navigationBarTitleDisplayMode(.inline)
        }
    }
}

struct MoonPhaseView: View {
    var phase : String
    
    var body: some View {
        HStack{
            Text("MoonPhaseView!")
            Text(phase)
        }
    }
}

struct MoonPhaseView_Previews: PreviewProvider {
    static var previews: some View {
        MoonPhaseView(phase: "Full")
    }
}

Note that every time MoonPhaseView is used, you must provide a phase parameter so that it has a value to fill var phase: String .请注意,每次使用MoonPhaseView时,都必须提供一个phase参数,以便它有一个值来填充var phase: String You could provide a default value, but that doesn't seem like it would do much good here.您可以提供一个默认值,但这似乎在这里没有多大用处。


Not directly related to your question, but I might suggest that calculating the phase in the body might lead to undesirable results, especially if it's an expensive calculation or it has to contact an API or something.与您的问题没有直接关系,但我可能建议计算body的相位可能会导致不良结果,特别是如果它是一个昂贵的计算或者它必须联系 API 或其他东西。 You might want to consider doing this in onAppear and keeping it in a @State variable in your ContentView , or perhaps even using an ObservableObject as a view model and storing the phase there.您可能需要考虑在onAppear中执行此操作并将其保存在ContentView中的@State变量中,或者甚至使用ObservableObject作为视图 model 并将相位存储在那里。

You can use "Environment" to pass system-wide settings to views and child views.您可以使用“环境”将系统范围的设置传递给视图和子视图。

For example:例如:

@main
struct TestApp: App {
    let moonPhaseValue = "Waxing"   // <--- some value 
    var body: some Scene {
        WindowGroup {
            ContentView().environment(\.moonPhase, moonPhaseValue) // <--- pass it around
        }
    }
}


struct ContentView: View {
    @Environment(\.moonPhase) var moonPhase   // <--- the value again
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: MoonPhaseView()) {
                    Text("Moon Phase - " + moonPhase)
                }
            }
        }.navigationViewStyle(StackNavigationViewStyle())
    }
}

struct MoonPhaseView: View {
    @Environment(\.moonPhase) var moonPhase  // <--- the value again
    var body: some View {
        HStack{
            Text("MoonPhaseView is \(moonPhase)")
        }
    }
}

// create your own EnvironmentKey
struct MoonPhaseKey: EnvironmentKey {
    static let defaultValue: String = "Full"
}
// create your own EnvironmentValues
extension EnvironmentValues {
    var moonPhase: String {
        get { return self[MoonPhaseKey] }
        set { self[MoonPhaseKey] = newValue }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 SwiftUI 中将变量从一个视图传递到另一个视图 - How to pass variable from one view to another in SwiftUI 如何将数据从一个 SwiftUI 视图文件传递到另一个? - How do I pass data from one SwiftUI view file to another? 如何将可选视图传递给 SwiftUI 中的另一个视图? - How to pass optional view to another view in SwiftUI? 从另一个视图将变量传递给 SwiftUI AVPlayer - Pass variable to SwiftUI AVPlayer from another view 如何通过将全局变量用于iMessage将值从一个自定义单元格传递到另一视图控制器? - How to pass values from one custom cell to another view controller by using global variables for iMessage? 如何在IOS中将数据从一个视图传递到另一个视图控制器? - How to pass data from one view to another view controller in IOS? 如何通过parentviewController将数据从一个视图传递到另一个视图 - how to pass data from one view to another view through parentviewcontroller 如何将值从一个视图传递到另一视图 - How to pass a value from one view to another view 如何将图像从一个视图传递到另一个视图 - how to pass images from one View to another View 如何将值从一个视图控制器传递到上一个视图控制器) - How to pass the values from one view controller to previous view controller)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM