onTapGesture 不适用于自定义视图

Dai*_*na 2 swiftui

我试图在选择按钮时更改按钮的颜色。当我按下按钮时没有任何变化。似乎 .onTapGesture 不适用于自定义视图。

我尝试使用 Buttons 而不是 .onTapGesture,但它也不起作用。.contentShape 不起作用。我也尝试过使用列表,效果很好。但我认为有更好的方法。

import SwiftUI

struct UserSettings: View {
    

@State private var selectedIndex: Int = 0

var body: some View {
   
        VStack {
            
                HStack(spacing: 0) {
                    
                    ForEach(0..<3) { subIndex in
                        let pat = customPatterns1[subIndex]
                                
                        PatternOptionView(pat: pat, isSelected: subIndex == selectedIndex)
                            .contentShape(Rectangle())

                       
                        .onTapGesture(perform: {
                            selectedIndex = subIndex
                        })
                    }
                }
               
                    
        }

}

}

struct UserSettings_Previews: PreviewProvider {
    static var previews: some View {
        UserSettings()
    }
}
Run Code Online (Sandbox Code Playgroud)

我的自定义视图:

    import SwiftUI

struct PatternOptionView: View {
    var pat: PatternView
    var isSelected: Bool

var body: some View {
    Button(action: {
        Settings.shared.pattern = pat.pattern
    }) {
        VStack{
            Rectangle()
                .fill(isSelected ? Color("Primary") : .white)
                .frame(width: UIScreen.main.bounds.width / 3, height: UIScreen.main.bounds.width / 3)
                .cornerRadius(15)
                .contentShape(Rectangle())
            
                .overlay(
                    Image(systemName: pat.image)
                        .font(.system(size: 28))
                        .foregroundColor(isSelected ? .white : Color("Primary"))
                )
            
            
            Text(pat.text)
                .foregroundColor(.secondary)
                .lineLimit(1)
        }
        
        //.padding()
    }.contentShape(Rectangle())
    
    
}
}

struct PatternOptionView_Previews: PreviewProvider {
    static var previews: some View {
        PatternOptionView(pat: customPatterns1[0], isSelected: true)
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

就我而言,我可以通过设置使其工作contentShape

PatternOptionView(pat: pat, isSelected: subIndex == selectedIndex)
    .contentShape(Rectangle())
    .onTapGesture(perform: {
        selectedIndex = subIndex
    })
Run Code Online (Sandbox Code Playgroud)