TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Observable class and binding it to alert sheet

Forums > SwiftUI

I am fooling around with latest Observable macro in iOS 17. Everything works, macro automatically annotates my Observable ViewModel properties as @ObservationTracked and I can just reference viewmodel properties in my Text views inside my view, even without explicitily using $ symbol. Nice. However my alert sheet for whathever reason cant be binded to viewmodel property "showingAlertNoHealthDataAccess".

Just for reference. Here is a piece of my code:

@Observable class MasterViewModelImpl: MasterViewModel {    
    var showingAlertNoHealthDataAccess = false

and my view

   var body: some View {
        TabView {
          SomeMoreViewsHere()
        .alert(isPresented: viewModel.showingAlertNoHealthDataAccess) {
            Alert(title: Text(viewModel.errorLabel))
        }
    }

problem arises on line .alert... as I said

Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>'

all other properties are successfuly binded to my Text views. All without explicity having to annotate them @Published

2      

@Stepan doesn't provide a lot of detail. So this is a guess.

my alert sheet for whathever reason cant be binded bound to viewmodel property "showingAlertNoHealthDataAccess".

Have you reviewed @twoStraws' latest sessions on SwiftData? While you're not using SwiftData, in video 4 of 8 he shares a lesson using the @Bindable property wrapper.

You may need this wrapper to tell a view that the variable you're using can be bound to an object defined elsewhere.

2      

Yes, sorry. English isnt my first language. Thing is... my viewModel is instantiated on App level and passed around via Environment wrapper. But in my App declaration it is defined with @Bindable wrapper like so. I will check that SwiftData tutorial to be sure

@main
struct FitAppApp: App {
    @Bindable var masterViewModel = MasterViewModelImpl()

    var sharedModelContainer: ModelContainer = {
        let schema = Schema([
            PushupsRecord.self,
        ])
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return try ModelContainer(for: schema, migrationPlan: FitAppMigrationPlan.self, configurations: [modelConfiguration])
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()

    var body: some Scene {
        WindowGroup {
            MasterView()
        }
        .modelContainer(sharedModelContainer)
        .environment(masterViewModel)
    }
}

2      

In SwiftUI, you can use the $ symbol to create a binding between a view and a property of its view model. For example, if you have a showingAlert property in your view model, you can bind it to an alert sheet like this: .alert(isPresented: $viewModel.showingAlert) { Alert(title: Text("Alert"), message: Text("This is an alert."), dismissButton: .default(Text("OK"))) }

2      

Hey @poolsapk, I know, but thats not what problem here is. I am no longer using ObservableObject for my ViewModel, but rather, trying to use new Observable macro that was introduced with iOS 17. And that should make all my ViewModel properties published (emitting values over time) automatically as soon as I hook those properties with my views. However for whathever reason, it doesnt work for my alert sheet. viewModel.showingAlertNoHealthDataAccess is not bindable. It should be bindable as soon as my ViewModel is anotated with Observable macro. And it works for all my Text views. But not for my alert sheet. I am asking why

2      

It seems like you're having an issue with binding the showingAlertNoHealthDataAccess property to your alert sheet. The error message you're encountering, "Cannot convert value of type 'Bool' to expected argument type 'Binding<Bool>'," is because the .alert modifier expects a Binding<Bool> for the isPresented parameter.

To resolve this, you can create a computed property that returns a binding to showingAlertNoHealthDataAccess. Here's how you can do it:

@Observable class MasterViewModelImpl: MasterViewModel {
    @Published var showingAlertNoHealthDataAccess = false

    var alertBinding: Binding<Bool> {
        Binding(
            get: { self.showingAlertNoHealthDataAccess },
            set: { self.showingAlertNoHealthDataAccess = $0 }
        )
    }

    var body: some View {
        TabView {
            SomeMoreViewsHere()
                .alert(isPresented: alertBinding) {
                    Alert(title: Text(viewModel.errorLabel))
                }
        }
    }
}

By creating the alertBinding computed property, you're providing the expected Binding<Bool> to the .alert modifier, and it should bind correctly to your showingAlertNoHealthDataAccess property. This should resolve the issue you're facing.

Source:checkmepcobill.pk/fesco-online-bill/

2      

Thanks very much @checkmepcobill. Turns out I couldnt use @Published propertyWrapper for showingAlertNoHealthDataAccess within my computed property alertBinding. So as long as I removed that @Published, it works. Binding<Bool> property has to be initalized within view class, and it can refernce classical boolean property stored within ViewModel class. Everything works now, many thanks sir!

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.