如何在SwiftUI中将变量从“较高视图”转换为“较低视图”?

时间:2020-09-29 20:39:16

标签: swift swiftui

我是SwiftUI的新手,我想知道如何使用 UserDefaults.standard.integer 将ContentView中的变量“ Selection”放入SettingView中。我认为使用@Binding是不可能的,对吧?

import SwiftUI
import Combine

struct ContentView: View {
    
    @State var Selection = UserDefaults.standard.integer(forKey: "Picker")
    @State var Detail = false
    
    var body: some View {
        VStack {
        Button(action: {
            self.Detail.toggle()
        }) {
            Text("click")
        }.sheet(isPresented: $Detail) {
            SettingView(showSheetView: self.$Detail)
        }
        
        Picker("", selection: $Selection) {
            Text("Selection1").tag(0)
            Text("Selection2").tag(1)
            } .pickerStyle(SegmentedPickerStyle()).padding(.horizontal, 89)
            .onReceive(Just(Selection)) {
                UserDefaults.standard.set($0, forKey: "Picker")
            }
        }
    }
}

struct SettingView: View {
   
    @Binding var showSheetView: Bool
    
    var body: some View {
        NavigationView {
                Text("Test")
                .navigationBarTitle(Text("Select something"))
                .navigationBarItems(trailing: Button(action: {
                    self.showSheetView = false
                }) {
                    Text("Ok")
                        .bold()
                        
            })
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用@Binding

.sheet(isPresented: $Detail) {
    // pass the `Selection` as a Binding
    SettingView(showSheetView: self.$Detail, selection: $Selection)
}
struct SettingView: View {
    @Binding var showSheetView: Bool
    @Binding var selection: Int // access as a Binding

    var body: some View {
        NavigationView {
            Text("Test \(selection)") // use as any other variable
            ...
        }
    }
}

注意:在命名Swift变量时,通常最好使用小写selection,而不是Selection