lorenzo
lorenzo

Reputation: 1743

SwiftUI PageView update outside view

I have a PageStyle TabView, and want to update a Text that is outside of it. I've used onAppear to get the page change event, and looks good at first if I scroll forward, but once I go backwards a few onAppear are missed.

Is this the correct way of doing this. Is is possible to do that?

struct PageView: View {
    
    @State var title: String = "hello"
    
    var body: some View {
        
        VStack {
            Text(self.title)
            TabView {
                ForEach(0..<100) { i in
                    Text("\(i)").onAppear {
                        self.title = ("TITLE = \(i)")
                    }
                }
            }
            .tabViewStyle(PageTabViewStyle())
        }
    }
}

Upvotes: 1

Views: 236

Answers (1)

Asperi
Asperi

Reputation: 257493

You can do this by using TabView(selection: and tag modifier on Text items, like below (tested with Xcode 12.1 / iOS 14.1)

var body: some View {
    VStack {
        Text(self.title)
        TabView(selection: $title){           // << here !!
            ForEach(0..<100) { i in
                Text("\(i)")
                   .tag(String(i))            // << here !!
            }
        }
        .tabViewStyle(PageTabViewStyle())
    }
}

Upvotes: 1

Related Questions