swiftui - 在swiftUI中按下TapBarItem时如何滚动到更大的NavigationTitle?
问题描述
我构建了一个简单的应用程序,它有两个 tapBarItem [主页和设置视图]。
在 home tapBarItem 中有带有 id 的颜色列表,当滚动到底部并按 home tapBarItem 然后它会自动滚动到列表中的第一个颜色。我想要实现的是能够滚动到更大的 NavigationTitle。如果您知道如何实现它,请告诉我[就像点击状态栏一样]。
这是代码:
import SwiftUI
struct ContentView: View {
@State private var scrollToTop = false
@State private var selection = 0
@State private var colors: [CustomColor] = [
CustomColor(id: 1, color: .red),
CustomColor(id: 2, color: .green),
CustomColor(id: 3, color: .blue),
CustomColor(id: 4, color: .orange),
CustomColor(id: 5, color: .purple),
CustomColor(id: 6, color: .yellow),
CustomColor(id: 7, color: .gray),
CustomColor(id: 8, color: .black)
]
var handler: Binding<Int> {
Binding(
get: { selection },
set: {
if $0 == selection {
scrollToTop.toggle()
}
selection = $0
}
)}
var body: some View {
TabView(selection: handler) {
NavigationView {
ZStack {
ScrollView {
ScrollViewReader { reader in
VStack(spacing: 20) {
ForEach(colors) { item in
item.color
// .tag(item.id)
.onChange(of: scrollToTop) { isTop in
if isTop {
withAnimation(.spring(response: 0.3)) {
reader.scrollTo(item.id - 1, anchor: .top)
}
}
}
.frame(
minWidth: 200,
idealWidth: 200,
maxWidth: .infinity,
minHeight: 300,
idealHeight: 500,
maxHeight: .infinity,
alignment: .center
)
}
}
.padding([.bottom], 20)
}
}
}
.navigationBarTitle(Text("Feed"))
}
.tabItem {
Image(systemName: "house")
.font(.title)
}
.tag(0)
Text("Second View")
.tabItem {
Image(systemName: "gearshape.2")
.font(.title)
}
.tag(1)
}
.accentColor(.black)
}
}
struct CustomColor: Identifiable {
let id: Int
let color: Color
}
解决方案
推荐阅读
- amazon-quicksight - 在 Quicksight 中仅显示月份
- python - 为什么 RecyleView 按钮的外观搞砸了?
- android - 如何在回收站视图中添加从左到右滑动
- c# - 引用面向多个框架 C# WPF 的项目时生成问题
- javascript - 国际电话输入问题
- angular - 无法在 Spartcus3.0.0-next.3 中使用 outletref 创建组件
- android - Delphi - Android - 将文本文件保存到内部存储
- character-encoding - Sybase ASE:显示数据库使用的字符编码
- c - C Unions:为什么我会为同一个地址得到两个不同的值?
- python - 在客户端运行后端功能的安全方法