Reputation: 490
Playing around with SwiftUI and this TapGesture() (or any other gesture) doesn't seem to work for me in a Cocoa app for MacOS, despite @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
when I View Definition on TapGesture.
import SwiftUI
struct CircleView : View {
var body: some View {
Circle()
.fill(Color.blue)
.frame(width: 400, height: 400, alignment: .center)
.gesture(
TapGesture()
.onEnded { _ in
print("View tapped!")
}
)
}
}
#if DEBUG
struct CircleView_Previews : PreviewProvider {
static var previews: some View {
CircleView()
}
}
#endif
The Build succeeded, I'm viewing the Circle in Preview and I have the console open, but nothing seems to print.
Am I doing something wrong? Is this a 10.15 Beta bug? Is there another framework I need to import other than SwiftUI? New to Swift here.
Upvotes: 2
Views: 1766
Reputation: 438232
The tap is working fine, but when you’re previewing the app, you won’t see your print
statements in the console. Actually run the app and you’ll see the print
statements show up in your console.
Or change your app to present something in the UI confirming the tap gesture, e.g., an Alert
:
struct CircleView : View {
@State var showAlert = false
var body: some View {
Circle()
.fill(Color.blue)
.tapAction {
self.showAlert = true
}
.presentation($showAlert) {
Alert(title: Text("View Tapped!"),
primaryButton: .default(Text("OK")),
secondaryButton: .cancel())
}
}
}
Or perhaps you would want to animate the change of color of the shape:
struct CircleView: View {
@State var isBlue = true
var body: some View {
Circle()
.fill(isBlue ? Color.blue : Color.red)
.tapAction {
withAnimation {
self.isBlue.toggle()
}
}
}
}
Upvotes: 1