1

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())
        }
    }
}
lorenzo
  • 1,487
  • 1
  • 17
  • 25

1 Answers1

1

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())
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690