gpt4 book ai didi

SwiftUI 如何在滑动 TabView 时访问 ScrollViewReader 的代理

转载 作者:行者123 更新时间:2023-12-05 06:48:09 24 4
gpt4 key购买 nike

目前,我创建了一个自定义导航,在其中选择各个选项卡(信息、比萨等)后,它会将我滑动到一个新 View 。基本上是 UIPageViewController 的 UIKit 等价物。

Something different that i did is that when a selecting a section, it will also animate the scrollView to center the text.因此,例如,如果我选择“意大利面”部分,它会将我滑动到正确的 View 并将“意大利面”文本置于 ScrollView 的中心。为了实现这一点,我在 ScrollView 中嵌入了一个 ScrollViewReader 以获得对代理的访问权限,并且每次我选择该部分时,我都会调用 proxy.scrollTo 来滚动到正确的索引。但是 TabView 是如何获取到 ScrollView 的代理的呢?所以现在,当我滑动到新 View 时,下一页的文本被选中,但 scrollView 不会滚动到索引并将其居中。

如果 TabView 被滑动,有什么方法可以通知 View ?所以我可以调用 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)
}
}
}
}
})

section as a scrollView

最佳答案

有一个开源库可以解决您的问题。可滚动样式使您选择的选项卡居中。

https://github.com/xmartlabs/PagerTabStripView#scrollable-style

关于SwiftUI 如何在滑动 TabView 时访问 ScrollViewReader 的代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66896932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com