Hey everyone, I'm in the awkward situation where I need to be able to show one of three different sheets based on whether or not an observed (@Published
) property on an @ObservedObject
is in a certain subset of possible enum cases. This may sound confusing, so let me try to demonstrate with a very reduced example:
class MyObservedClass: ObservableObject {
// initialisation...
enum PossibleStates {
case caseA
case caseB
case caseC
case caseD
case caseE
}
@Published var state: PossibleStates
}
struct Test: View {
@ObservedObject var myObservedClass: MyObservedClass
@State private var sheetToShow: SheetToShow?
var body: some View {
Rectangle()
.sheet(item: $sheetToShow) { item in
switch item {
// show different sheets based on case
}
}
}
private enum SheetToShow: Int, Identifiable {
case showSheet1
case showSheet2
case showSheet3
var id: Int { self.rawValue }
}
}
I need to be able to set sheetToShow
based on conditions like:
if [.caseA, .caseB].contains(myObservedClass.state) {
sheetToShow = .showSheet1
} else if [.caseC, .caseD].contains(myObservedClass.state) {
sheetToShow = showSheet2
} else {
sheetToShow = showSheet3
}
But sheetToShow
also needs to be an @State
variable I can use in the sheet(item:)
call and that can be set to nil
when no sheet is to be shown, or a sheet has been dismissed, and sheetToShow
needs to update whenever myObservedClass.state
changes.
Is there any halfway sane way to achieve this, and have it update correctly (and not just, for example, when the Test
view gets initialised, or appears)? 🤔