buttonswiftuiobservedobject

I want to click a button inside the First View and pass a Bool to the ContentView to show the secondView inside ContentView. How i can do it?


I make Observable class with Published var

I want to click a button inside the First View and pass a Bool to the ContentView to show the secondView inside ContentView. How i can do it?

The code in my First View is:

class ShowPicker: ObservableObject {
    @Published var pickerIsShow = false
}



struct FirstView: View {
    
    @ObservedObject var showPicker = ShowPicker()
    
    var body: some View {
        
        VStack{
            
            Button("showPicker"){
                self.showPicker.pickerIsShow.toggle()
            }
        }
    }
    
}


The code in my ContenView is:

struct ContentView: View {
    
    @ObservedObject var showPicker = ShowPicker()

    var body: some View {
        
        VStack {

           FirstView() 
            
            secondView().offset(y: self.showPicker.pickerIsShow ? 0 : UIScreen.main.bounds.height)
   
        }
    }
}


Solution

  • This does not work because you declare 2 different instances of ShowPicker. Try:

    struct FirstView: View {
        // Wrap your ShowPicker in an EnvironmentObject in order to access the same instance as the ContentView
        @EnvironmentObject private var showPicker: ShowPicker
        
        var body: some View {
            
            VStack{
                
                Button("showPicker"){
                    self.showPicker.pickerIsShow.toggle()
                }
            }
        }
        
    }
    
    struct ContentView: View {
        // Wrap your ShowPicker in an StateObject and create it.
        @StateObject private var showPicker = ShowPicker()
    
        var body: some View {
            
            VStack {
               // pass your ShowPicker to your FirstView as an environmentObject
               FirstView()
                   .environmentObject(showPicker) 
                
                secondView().offset(y: self.showPicker.pickerIsShow ? 0 : UIScreen.main.bounds.height)
       
            }
        }
    }
    

    This way both Views have access to the same instance of ShowPicker and can react to changes of each other.