How to force a refresh of a SwiftUI View?

How to force a refresh of a SwiftUI View?

Problem Description:

I have a button with a .disabled() condition that’s a computed property of my ObservableObject model class. This means I can’t make it @Published.

Something like this:

class MyModel : ObservableObject {
    var isDisabled: Bool {
        if ... {
            return true
        else {
            return false

struct SettingsNewsSubscriptionsView : View {
    @ObservedObject var model: MyModel

    var body: some View {

        Button("Save") {
            Task {
                // Saves to backend asynchronously, then updates MyModel which changes isDisabled.

At some point isDisabled is false. When the button is tapped something is saved asynchronously after which MyModel is updated which will result in isDisabled to become true.

Because isDisabled is not @Published, the button does not update once isDisabled becomes true.

How can I trigger the refresh of a SwiftUI View, in this case Button explicitly from within a Task?

Solution – 1

You can try making the property stored instead of computed, that way you can use @Published

Solution – 2


Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.