【发布时间】:2021-04-01 00:24:49
【问题描述】:
目前,我创建了一个自定义导航,在其中选择单个选项卡(信息、披萨等),它会将我滑动到新视图。基本上相当于 UIPageViewController 的 UIKit。
Something different that i did is that when a selecting a section, it will also animate the scrollView to center the text.因此,例如,如果我选择“Pasta”部分,它会将我滑动到正确的视图并在 scrollView 中居中放置“Pasta”文本。为了实现这一点,我在 ScrollView 中嵌入了一个 ScrollViewReader 以获得对代理的访问权限,并且每次我选择该部分时,我都会调用 proxy.scrollTo 以滚动到正确的索引。但是 TabView 是如何访问 ScrollView 的代理的呢?所以现在,当我滑动到新视图时,下一页的文本被选中,但 scrollView 不会滚动到索引并居中。
如果 TabView 被滑动,有什么方法可以通知视图吗?所以我可以调用scrollTo?
struct CustomNavigationView: View {
@State var activeIndex = 0
var body: some View {
VStack(spacing: 0) {
AppBar(index: self.$activeIndex)
TabView(selection: self.$activeIndex,
content: {
First()
.tag(0)
RecommendationPage()
.tag(1)
NewView(text: "Third", color: Color.orange)
.tag(2)
})
///Allows the swipe to happen
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
}
.animation(.default)
.edgesIgnoringSafeArea(.all)
}
}
struct AppBar: View {
@Binding var index: Int
var sections = ["Episode", "Related Shows", "About", "Info", "Pizza", "Hamburger", "Pasta", "I dont even know"]
var body: some View {
VStack(alignment: .leading) {
Text("Home")
...
ScrollView(.horizontal, showsIndicators: false, content: {
ScrollViewReader { proxy in
VStack(alignment: .leading) {
//Underline bar
ZStack(alignment: .leading) {
...
}
///Sections
HStack(spacing: tabsSpacing) {
ForEach(0..<sections.count) { i in
Button(action: {
self.index = i
withAnimation(.linear) {
///This checks ensures that when we select last 2 items, scrollView doesnt try to align selectedIndex to middle
if i < sections.count - 2 {
proxy.scrollTo(i, anchor: .center)
} else if i == sections.count - 2 {
proxy.scrollTo(i)
} else {
proxy.scrollTo(i, anchor: .trailing)
}
}
}, label: {
Text(sections[i])
...
})
.id(i)
}
}
}
}
})
【问题讨论】:
标签: swiftui