首页 > 解决方案 > 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)
}
}

标签: swiftui

解决方案


我尝试将您的代码置于某种可构建状态,但我无法编译或运行它,所以我可能完全误解了您正在尝试做的事情。但是,在我看来,您使用pressed的好像是在捕获该特定SectionView. 但是,它必须是一个 State var 才能编译,所以它会更新所有的视图,这就是我相信你所看到的。我认为您需要做的是更改pressed为一个 Int 来跟踪SectionView被按下的,并将其与让特定SectionView跟踪其身份的数字进行比较。

另外,我不认为你想要SectionView点击手势。我认为您只想更改按下变量的状态并让它通过层次结构工作。


推荐阅读