11

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"

1 Answer 1

21

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
Sign up to request clarification or add additional context in comments.

1 Comment

This and the answer here solved my problem, thanks

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.