8

I would like to change the value of a text when the active tab of a TabView changes. I tried using onChange(of: activeTab, perform: {}) to change the value of the state variable that stores the text but it seems that the closure given to onChange() is never called.

TabView(selection: $activeTab) {
  ForEach(exampleData) {dayMenu in
    DayMenuView(dayMenu: dayMenu)
      .padding([.leading, .bottom, .trailing])
  }
}
.onChange(of: activeTab, perform: { index in
  print(activeTab)
  withAnimation {
    activeDate = dates[1]
  }
})

Text view

Text(activeDate)

State variables

let dates = ["Montag", "Dienstag"]
    
@State private var activeTab: Int = 0
@State private var activeDate = "Montag"

derivmug
  • 163
  • 1
  • 7

1 Answers1

15

Provided code is not testable but I think it is because activeTab is not changed because tab views are not identified, due to tag, so try

TabView(selection: $activeTab) {
  ForEach(exampleData.indices, id: \.self) { index in
    DayMenuView(dayMenu: exampleData[index])
      .padding([.leading, .bottom, .trailing])
      .tag(index)
  }
}
.onChange(of: activeTab, perform: { index in
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • This and the answer [here](https://stackoverflow.com/questions/59157595/how-to-animate-transition-text-value-change-in-swiftui) solved my problem, thanks – derivmug Dec 10 '20 at 20:23