1

There is an array of Views, and whenever the currentPosition variable changes, the view must change. However it is not changing.

I have a global ObservableObject class that has an array of Views, and a currentPosition value. My goal is to have the view changed according to the currentPosition variable.

class AXGlobalValues: ObservableObject {
    @Published var tabs: [AXTabItem] = [
        .init(webView: AXWebView()),
        .init(webView: AXWebView())
    ]
    
    @Published var currentPosition: Int = 0
}

On the SwiftUI view, I wrote global.tabs[global.currentPosition].webView, and I was expecting the webView to change based on the global.currentPosition value. However it didn't change.

What I tried to do was add an onChange(of:), but since SwiftUI is a declarative language, I couldn't update the view.

struct AXTabView: View {
    @EnvironmentObject private var global: AXGlobalValues

    
    var body: some View {
        Text("\(global.currentPosition)")
        
        global.tabs[global.currentPosition].webView
            .onChange(of: global.currentPosition) { newValue in
                // Not allowed in SwiftUI :(
                global.tabs[global.currentPosition].webView
            }
    }
}

Is there any way I can update the view based on the currentPosition variable?

Thanks in advance!

1
  • I have updated it now. Commented Nov 13, 2022 at 0:56

1 Answer 1

1

ObservableObject is part of the Combine framework and is designed to persist (or sync) a data model, it's not the right place to store SwiftUI View structs.

Also, for view data like currentPosition we usually use @State var with simple values or a custom struct when we want to group some related vars or have extra logic. body is recomputed when the @State changes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.