Home > other >  SwiftUI: Have the nth view from an array swapped out when the currentIndex value changes?
SwiftUI: Have the nth view from an array swapped out when the currentIndex value changes?

Time:11-16

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!

CodePudding user response:

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.

  • Related