gpt4 book ai didi

swift - 如何在 Swift UIKit Map 组件中处理 SwiftUI 中的触摸手势?

转载 作者:行者123 更新时间:2023-11-28 13:29:47 25 4
gpt4 key购买 nike

我尝试在 SwiftUI 应用程序中处理 Map UIKit 组件手势。Xcode 显示此警告:“字符串文字不是有效的 Objective-C 选择器”

// Binding to UIKit component

import SwiftUI
import MapKit

struct MapView: UIViewRepresentable {

class Coordinator: NSObject, MKMapViewDelegate {
@Binding var selectedPin: MapPin?

init(selectedPin: Binding<MapPin?>) {
self._selectedPin = selectedPin
}

func mapView(_ mapView: MKMapView,
didSelect view: MKAnnotationView) {
guard let pin = view.annotation as? MapPin else {
return
}
pin.action?()
selectedPin = pin
}

func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
guard (view.annotation as? MapPin) != nil else {
return
}
selectedPin = nil
}
}

@Binding var pins: [MapPin]
@Binding var selectedPin: MapPin?

func makeCoordinator() -> Coordinator {
return Coordinator(selectedPin: $selectedPin)
}

func makeUIView(context: Context) -> MKMapView {
let view = MKMapView(frame: .zero)
let gRecognizer = UITapGestureRecognizer(target: self, action: #selector(triggerTouchAction(gestureRecognizer:)))
view.addGestureRecognizer(gRecognizer)
view.delegate = context.coordinator
return view
}

func updateUIView(_ uiView: MKMapView, context: Context) {
uiView.removeAnnotations(uiView.annotations)
uiView.addAnnotations(pins)
if let selectedPin = selectedPin {
uiView.selectAnnotation(selectedPin, animated: false)
}
}

@objc func triggerTouchAction(gestureReconizer: UITapGestureRecognizer) {
//Add alert to show it works
print("Hello, tap!")
}
}

我希望在我的 Xcode 控制台中收到消息,但没有产生触摸事件。

环境:Xcode 11 测试版 6macOS Mojave 10.14.6

最佳答案

@objc 不能应用于结构内部的函数。将函数移到 Coordinator 中,然后以这种方式更改 UIGestureRecognizer 声明:

let gRecognizer = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.triggerTouchAction(gestureReconizer:)))

关于swift - 如何在 Swift UIKit Map 组件中处理 SwiftUI 中的触摸手势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57577901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com