Search code examples
swiftuigesture

Is the SwiftUI tapGesture super greedy?


Swift 5, iOS 13

This code works if I change the second Gesture to say a LONG Press, but leave them both as tap and it never shows the red box? Am I going mad?

import SwiftUI

struct SwiftUIViewQ: View {
@State var swap: Bool = false
var body: some View {
  VStack {
    if swap {
      SquareView(fillColor: Color.red)
      .onTapGesture {
        self.swap = false
      }
    } else {
      SquareView(fillColor: Color.blue)
      .onTapGesture {
        self.swap = true
      }
    }
  }
}
}

struct SquareView: View {
@State var fillColor: Color
var body: some View {
    Rectangle()
      .fill(fillColor)
      .frame(width: 128, height: 128)
      .onAppear {
        print("fillColor \(self.fillColor)")
      }
}
}

Oddly if I add an onAppear to the first view, it works... if I than add an onAppear to the second it breaks it again..


Solution

  • var fillColor doesn't need @State, just remove that and it'll work fine

    struct SquareView: View {
        var fillColor: Color
        var body: some View {
            Rectangle()
              .fill(fillColor)
              .frame(width: 128, height: 128)
              .onAppear {
                print("fillColor \(self.fillColor)")
              }
        }
    }