swift - 如何在 SwiftUI 中检测点击手势位置?
问题描述
(对于 SwiftUI,而不是 vanilla UIKit)非常简单的示例代码,例如,在灰色背景上显示红色框:
struct ContentView : View {
@State var points:[CGPoint] = [CGPoint(x:0,y:0), CGPoint(x:50,y:50)]
var body: some View {
return ZStack {
Color.gray
.tapAction {
// TODO: add an entry to self.points of the location of the tap
}
ForEach(self.points.identified(by: \.debugDescription)) {
point in
Color.red
.frame(width:50, height:50, alignment: .center)
.offset(CGSize(width: point.x, height: point.y))
}
}
}
}
我假设我需要 TapGesture 或其他东西,而不是 tapAction?但即使在那里,我也看不到任何获取水龙头位置信息的方法。我该怎么办?
解决方案
好吧,经过一番修补并感谢我对另一个问题的回答,我找到了一种使用 UIViewRepresentable 的方法(但无论如何,如果有更简单的方法,请告诉我!)这段代码有效为了我!
struct ContentView : View {
@State var points:[CGPoint] = [CGPoint(x:0,y:0), CGPoint(x:50,y:50)]
var body: some View {
return ZStack(alignment: .topLeading) {
Background {
// tappedCallback
location in
self.points.append(location)
}
.background(Color.white)
ForEach(self.points.identified(by: \.debugDescription)) {
point in
Color.red
.frame(width:50, height:50, alignment: .center)
.offset(CGSize(width: point.x, height: point.y))
}
}
}
}
struct Background:UIViewRepresentable {
var tappedCallback: ((CGPoint) -> Void)
func makeUIView(context: UIViewRepresentableContext<Background>) -> UIView {
let v = UIView(frame: .zero)
let gesture = UITapGestureRecognizer(target: context.coordinator,
action: #selector(Coordinator.tapped))
v.addGestureRecognizer(gesture)
return v
}
class Coordinator: NSObject {
var tappedCallback: ((CGPoint) -> Void)
init(tappedCallback: @escaping ((CGPoint) -> Void)) {
self.tappedCallback = tappedCallback
}
@objc func tapped(gesture:UITapGestureRecognizer) {
let point = gesture.location(in: gesture.view)
self.tappedCallback(point)
}
}
func makeCoordinator() -> Background.Coordinator {
return Coordinator(tappedCallback:self.tappedCallback)
}
func updateUIView(_ uiView: UIView,
context: UIViewRepresentableContext<Background>) {
}
}
推荐阅读
- python - 递归观察者看不到所有目录
- r - 基于三种集合格式提取字符串的多个部分
- asp.net-mvc - where 语句 - 选择列表返回所有值
- javascript - 附加元素与 innerHTML
- inno-setup - 是否可以在 InitializeSetup 中获取应用程序目录路径?
- scala - 如何将数据框或 RDD 转换为元组列表?
- python - 如何使用 python pandas 从 SQL Server 创建超过 700 MB 数据的 DataFrame
- java - 动态访问 Java 类的成员变量
- python - Plotly Dash 表回调 v2
- java - countDownLatch.await() 超时时记录