Reputation: 215
I´m new in SwiftUI and I would know how can I get the variable "Selection" from ContentView into SettingView in my "special" case with UserDefaults.standard.integer. I think with @Binding is it not possible, right?
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()
})
}
}
}
Upvotes: 0
Views: 65
Reputation: 54466
You can use @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
...
}
}
}
Note: it's generally better to use lowercase when naming Swift variables, ie. selection
and not Selection
.
Upvotes: 2