我想检测用户何时在滚动视图上滚动并在某个滚动项上方显示一个按钮,我在网上查找一些示例时编写了这段代码,但没有打印出滚动ID的更改,为什么?
ScrollView {
LazyVGrid(columns: columns) {
ForEach(group) { g in
NavigationLink {
Text("Details")
} label: {
VStack {
Image(systemName: "tv") // Replace with actual images
.resizable()
.scaledToFit()
.frame(width: reader.size.width/3, height: 50)
.padding()
.background(Color.gray.opacity(0.2))
.cornerRadius(10)
Text("List")
.bold()
.font(.subheadline)
}
.foregroundStyle(.white)
}
}
}
.scrollTargetLayout()
}
.scrollPosition(id: $scrollID)
我尝试了你的例子,即兴创作了缺少的部分。
这对我有用。当网格滚动时,会打印
LazyVGrid
第一列中的项目 ID。所以问题可能出在您未发布的代码中的某个地方。
这是更新的示例:
struct ContentView: View {
struct Group: Identifiable {
let id = UUID()
}
let columns = [GridItem(.flexible()), GridItem(.flexible())]
let group: [Group]
@State private var scrollID: Group.ID?
init() {
var groups = [Group]()
for i in 0..<100 {
groups.append(Group())
}
self.group = groups
}
var body: some View {
GeometryReader { reader in
ScrollView {
LazyVGrid(columns: columns) {
ForEach(group) { g in
NavigationLink {
Text("Details")
} label: {
VStack {
Image(systemName: "tv") // Replace with actual images
.resizable()
.scaledToFit()
.frame(width: reader.size.width/3, height: 50)
.padding()
.background(Color.gray.opacity(0.2))
.cornerRadius(10)
Text("\(g.id)") // "List"
.bold()
.font(.subheadline)
}
.foregroundStyle(.white)
}
}
}
.scrollTargetLayout()
}
.scrollPosition(id: $scrollID)
.onChange(of: scrollID) { oldVal, newVal in
print("\(String(describing: newVal))")
}
}
}
}