4

我想在 TabView 的活动选项卡更改时更改文本的值。我尝试使用onChange(of: activeTab, perform: {})来更改存储文本的状态变量的值,但似乎onChange()从未调用给定的闭包。

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(activeDate)

状态变量

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

4

1 回答 1

6

提供的代码不可测试,但我认为这是activeTab因为标签未识别标签视图而未更改,因此请尝试

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
于 2020-12-10T17:40:13.540 回答