具有一些渲染的图像,需要确定相对于图像的拍子位置。看起来很简单,但是找不到答案
var body: some View {
VStack {
Image(uiImage: drawRectangle()) // some rendered image
.onTapGesture {
// print(x, y)?
}
答案 0 :(得分:1)
找到了这个解决方案:
.gesture(
DragGesture(minimumDistance: 0, coordinateSpace: .global)
.onChanged { value in
self.position = value.location
}
.onEnded { _ in
self.position = .zero
}
)
设置minimumDistance: 0
将立即调用onChanged
答案 1 :(得分:1)
我确实尝试将DragGesture
与minimumDistance: 0
一起使用,但是它劫持了表格视图的滚动手势。
因此,我更喜欢使用适当的UITapGestureRecognizer
添加到嵌入在UIView
SwitUI TappableView
中的普通透明UIViewRepresentable
中。
struct TappableView: UIViewRepresentable
{
var tapCallback: (UITapGestureRecognizer) -> Void
typealias UIViewType = UIView
func makeCoordinator() -> TappableView.Coordinator
{
Coordinator(tapCallback: self.tapCallback)
}
func makeUIView(context: UIViewRepresentableContext<TappableView>) -> UIView
{
let view = UIView()
view.addGestureRecognizer(UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.handleTap(sender:))))
return view
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<TappableView>)
{
}
class Coordinator
{
var tapCallback: (UITapGestureRecognizer) -> Void
init(tapCallback: @escaping (UITapGestureRecognizer) -> Void)
{
self.tapCallback = tapCallback
}
@objc func handleTap(sender: UITapGestureRecognizer)
{
self.tapCallback(sender)
}
}
}
然后只需将其作为.overlay
添加到要添加水龙头的SwiftUI视图中即可。
.overlay(
TappableView { gesture in
// Just use the regular UIKit gesture as you want!
})