问题描述
我在 SwiftUI 中遇到了一个奇怪的问题.我创建了一个只包含一个按钮的简单视图和一个使用 PageViewStyle 的 TabView.TabView 似乎没有更新它的内容正确取决于变量的状态.似乎内容以某种方式更新,但视图不会像我期望的那样更新
I came across a weird Issue in SwiftUI.I created a simple View that only holds a Buttonand a TabView that uses the PageViewStyle. It seems that the TabView does not update it's contentcorrectly depending on the State of the Variable.It seems that the content gets updated somehow but the View wont be updated how I would expect
这是我的视图代码:
struct ContentView: View {
@State var numberOfPages: Int = 0
@State var selectedIndex = 0
var body: some View {
VStack {
Text("Tap Me").onTapGesture(count: 1, perform: {
self.numberOfPages = [2,5,10,15].randomElement()!
self.selectedIndex = 0
})
TabView(selection: $selectedIndex){
ForEach(0..<numberOfPages, id: \.self) { index in
Text("\(index)").background(Color.red)
}
}
.frame(height: 300)
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .automatic))
}.background(Color.blue)
}
}
这是多次点击标签后的结果.初始状态不是 0 页.在您点击后,我希望TabView 会发生变化,因此所有页面都可以滚动和可见,但由于某种原因,只有页面指示器会更新它的状态.
This is how the result looks after tapping the label several Times.The Initial State is no 0 Pages. After you tap i would expect that the content of theTabView changes so all Pages will be scrollable and visible but just the page indicator updates it State for some reason.
推荐答案
TabView
希望有页面容器,但你只包含了一个 HStack
(有自己的动态内容),此外链接页数你必须重置标签视图,所以这里是一个修复.
TabView
expects to have container of pages, but you included only one HStack
(with own dynamic content), moreover chaining number of pages you have to reset tab view, so here is a fix.
使用 Xcode 12/iOS 14 测试
Tested with Xcode 12 / iOS 14
struct ContentView: View {
@State var numberOfPages: Int = 0
var body: some View {
VStack {
Text("Tap Me").onTapGesture(count: 1, perform: {
self.numberOfPages = [2,5,10,15].randomElement()!
})
if self.numberOfPages != 0 {
TabView {
ForEach(0..<numberOfPages, id: \.self) { index in
Text("\(index)").frame(width: 300).background(Color.red)
}
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .automatic))
.frame(height: 300)
.id(numberOfPages)
}
}
}
}
这篇关于带有“PageTabViewStyle"的 TabView@State var 更改时不更新其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!