SwiftUI can't tap in Spacer of HStack

前端 未结 7 495
北海茫月
北海茫月 2020-12-28 12:08

I\'ve got a List view and each row of the list contains an HStack with some text view(\'s) and an image, like so:

HStack{
    Text(group.name)
    Spacer()
          


        
相关标签:
7条回答
  • 2020-12-28 12:32

    As I've recently learned there is also:

    HStack {
      ...
    }
    .contentShape(Rectangle())
    .onTapGesture { ... }
    

    Works well for me.

    0 讨论(0)
  • 2020-12-28 12:34

    Why not just use a Button?

    Button(action: { self.groupSelected(self.group) }) {
        HStack {
            Text(group.name)
            Spacer()
            if (groupModel.required) { Text("Required").color(Color.gray) }
            Image("ic_collapse").renderingMode(.template).rotationEffect(Angle(degrees: 90)).foregroundColor(Color.gray)
        }
    }.foregroundColor(.primary)
    

    If you don't want the button to apply the accent color to the Text(group.name), you have to set the foregroundColor as I did in my example.

    0 讨论(0)
  • 2020-12-28 12:37

    I've filed feedback on this, and suggest you do so as well.

    In the meantime an opaque Color should work just as well as Spacer. You will have to match the background color unfortunately, and this assumes you have nothing to display behind the button.

    0 讨论(0)
  • 2020-12-28 12:38

    works like magic on every view:

    extension View {
            func onTapGestureForced(count: Int = 1, perform action: @escaping () -> Void) -> some View {
                self
                    .contentShape(Rectangle())
                    .onTapGesture(count:count, perform:action)
            }
        }
    
    0 讨论(0)
  • 2020-12-28 12:43

    I just add the background color(except clear color) for HStack works.

    HStack {
            Text("1")
            Spacer()
            Text("1")
    }.background(Color.white)
    .onTapGesture(count: 1, perform: {
    
    })
    
    0 讨论(0)
  • 2020-12-28 12:52

    I've been able to work around this by wrapping the Spacer in a ZStack and adding a solid color with a very low opacity:

    ZStack {
        Color.black.opacity(0.001)
        Spacer()
    }
    
    0 讨论(0)
提交回复
热议问题