drago
drago

Reputation: 1283

Accessing a Private Variable in different Views in SwiftUI?

I'm trying to hide a view that's presented using .fullScreenCover(...) in my swiftui app.

I have this code in my contentView.swift

@State private var ShowSecondView = true

I also have this in my homeView.swift

struct homeView: View {
    
    
    @Binding var ShowSecondView: Bool

......

I present another view from my homeView like so:

.fullScreenCover(isPresented: $ShowSecondView, content: SecondView.init)

Now, I need to hide/dismiss the SecondView by pressing a button inside the SecondView.

But I'm currently getting this error in my homeView which is preventing me from compiling the app:

enter image description here

Could someone please advice on this issue?

Upvotes: 0

Views: 114

Answers (1)

aheze
aheze

Reputation: 30308

You also need to initialize showAudioPlayer and any other properties that don't have a default value.

init(tabSelection: Binding<Int>, showAudioPlayer: Binding<Bool>) {
    _tabSelection = tabSelection
    _showAudioPlayer = showAudioPlayer
}

Also, replace homeView's @Binding var ShowSecondView: Bool with:

/// inside homeView
@State var ShowSecondView = false

...because you are presenting SecondView from homeView. Use State in the parent view, and Binding inside any child view.

SecondView is a child view, so you need to put the binding there.

/// inside SecondView
@Binding var ShowSecondView: Bool

Then, pass in the Binding here:

.fullScreenCover(isPresented: $ShowSecondView, content: SecondView(ShowSecondView: $ShowSecondView))

Upvotes: 1

Related Questions