user13046968
user13046968

Reputation:

Conditionally present ActionSheet SwiftUI

I created an update sheet to inform my users about updates, but I don't want it to display every time I push an update because sometimes it's just bug fixes, so I created a constant to toggle the sheet. I'm calling the sheet below:

VStack {
    Text(" ")
}
.sheet(isPresented: $isShowingAppStoreUpdateNotification) {
    UpdatesView()
}

How can I conditionally check for the constant? This is what I tried:

if(generalConstants.shouldShowUpdateSheet) {
    .sheet(isPresented: $isShowingAppStoreUpdateNotification) {
        UpdatesView()
    }
}

But I get this error: Cannot infer contextual base in reference to member 'sheet'

Upvotes: 1

Views: 1182

Answers (2)

New Dev
New Dev

Reputation: 49590

.sheet is an instance method VStack, so you can't do what you did - it's not a legal Swift syntax.

The simplest approach is to have the condition over the VStack view:

if(generalConstants.shouldShowUpdateSheet) {
   VStack {
      Text(" ")
   }
   .sheet(isPresented: $isShowingAppStoreUpdateNotification) {
      UpdatesView()
   }
} else {
   VStack {
      Text(" ")
   }
}

but, of course, this isn't very DRY.

Instead, keep the logic of how the view behaves in the view model / state, and let the View just react to data changes. What I mean is, only set isShowingAppStoreUpdateNotification to true when all the conditions that you want are satisfied, and keep the view as-is

@State var isShowingAppStoreUpdateNotification = generalConstants.shouldShowUpdateSheet

var body: some View {
   VStack {
      Text(" ")
   }
   .sheet(isPresented: $isShowingAppStoreUpdateNotification) {
      UpdatesView()
   }
}

Upvotes: 1

Dscyre Scotti
Dscyre Scotti

Reputation: 1427

Here is my sample code.

struct ContentView: View {
    @State private var showSheet = false
    @State private var toggle = false {
        didSet {
            self.showSheet = toggle && sheet
        }
    }
    @State private var sheet = false {
        didSet {
            self.showSheet = toggle && sheet
        }
    }
    var body: some View {
        VStack {
            Toggle(isOn: $toggle) {
                Text("Allow to show sheet")
            }
            Button(action: {
                self.sheet.toggle()
            }) {
                Text("Show sheet")
            }
        }.sheet(isPresented: $showSheet, content: {
            Text("Sheet")
        })
    }
}

Upvotes: 0

Related Questions