swiftui - SwiftUI - 如何使用 onTapGesture 在 ScrollView 中仅初始化一个 SectionView
问题描述
我的问题是,当用户按下 ScrollView 中的项目时,所有 SectionView 项目都会发生变化。我想要做的是只更改一项。我试图在用户点击它时更改项目图像,然后当用户点击另一个项目以带回以前的项目图像并更改当前项目图像时。
看看我的 ScrollView:
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 15) {
ForEach(1..<41) { item in
GeometryReader { geometry in
SectionView(number: item, pressed: pressed, firstElement: (item == 1) ? true : false)
.rotation3DEffect(Angle(degrees:
Double(geometry.frame(in: .global).minX - 30) / -20
), axis: (x: 0, y: 10, z: 0))
.onTapGesture {
self.pressed.toggle()
SectionView(number: item, pressed: self.pressed, firstElement: (item == 1) ? true : false)
print("touched item \(item)")
}
})
}
}
}
这是我的剖面视图:
struct SectionView: View {
var number: Int
var pressed: Bool
var firstElement: Bool
var body: some View {
ZStack(alignment: .bottom) {
Image(pressed ? "t1" : "t\(number)")
.resizable()
.frame(maxWidth: .infinity)
.frame(maxHeight: .infinity)
.aspectRatio(contentMode: .fill)
Spacer()
Text(firstElement ? "" : "Pride")
.font(.system(size: 12, weight: .black))
.foregroundColor(.white)
.frame(maxWidth: .infinity, alignment: .center)
.padding(.bottom, 15)
}
.frame(width: 60, height: 80)
//.background(section.image)
.cornerRadius(7)
//.shadow(color: section.image.opacity(0.15), radius: 8, x: 0, y: 10)
}
}
解决方案
我尝试将您的代码置于某种可构建状态,但我无法编译或运行它,所以我可能完全误解了您正在尝试做的事情。但是,在我看来,您使用pressed
的好像是在捕获该特定SectionView
. 但是,它必须是一个 State var 才能编译,所以它会更新所有的视图,这就是我相信你所看到的。我认为您需要做的是更改pressed
为一个 Int 来跟踪SectionView
被按下的,并将其与让特定SectionView
跟踪其身份的数字进行比较。
另外,我不认为你想要SectionView
点击手势。我认为您只想更改按下变量的状态并让它通过层次结构工作。
推荐阅读
- javascript - 使用 create 和 post 模拟 axios,jestjs
- javascript - Javascript 加载显示
- javascript - 在不重新加载的情况下更改 HTML 页面上的特定元素
- javascript - 从单独的 html 文件加载后无法操作 html 元素 CSS 属性
- svg - 没有运气调整 svg 剪辑路径的大小
- bash - Bash 脚本无法比较 SHA-512 加盐哈希。得到错误的输出
- vb.net - 如何在 vb.net 应用程序中嵌入 Youtube 视频?
- linux - 为什么我不能在自修改代码中单步进入 aeskeygenassist 指令?
- c++ - 我在哪里可以找到库“version.lib”以便成功调用 GetFileVersionInfoSize()?
- node.js - 如何在 Next 中处理不同的 .env 文件?