没有与ObjectiveC的桥梁,我们可以在SwiftUI中单独获得水龙头的坐标吗?

问题描述 投票:0回答:1

我有以下代码:

    struct MyLocationMap: View {

    @EnvironmentObject var userData: UserData
    @State var annotationArray: [MyAnnotation] = [MyAnnotation(coordinates: CLLocationCoordinate2D(latitude: CurrentLocation().coordinates?.latitude ?? CLLocationCoordinate2D().latitude, longitude: CurrentLocation().coordinates?.longitude ?? CLLocationCoordinate2D().longitude), type: .waypoint)]

    var body: some View {

        MakeMapView(annotationArray: annotationArray)
        .gesture(
        LongPressGesture(minimumDuration: 1)
        .onEnded { _ in
            print("MapView pressed!\n--------------------------------------\n")
            //Handle press here

        })
    }
}

import SwiftUI
import CoreLocation
import MapKit

struct MakeMapView : UIViewRepresentable {
    typealias UIViewType = MKMapView

    let annotationArray: [MyAnnotation]?



    func makeUIView(context: UIViewRepresentableContext<MakeMapView>) -> MKMapView{
        MKMapView()
    }




    func updateUIView(_ mapView: MKMapView, context: Context) {



        mapView.showsUserLocation = true


        if let coordinates = CurrentLocation().coordinates {

            //            updateAnnotations(from: mapView)

            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {

                mapView.showsUserLocation = true
                mapView.showsCompass = true
                mapView.showsScale = true
                mapView.mapType = .satellite
                let span = MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002)
                let region = MKCoordinateRegion(center: coordinates, span: span)
                mapView.setRegion(region, animated: true)
            })

        }
    }

我遇到的麻烦是仅通过SwiftUI / Combine实现func convert(_ point: CGPoint, toCoordinateFrom view: UIView?) -> CLLocationCoordinate2D以获取手势的经度/纬度。可能吗?如果没有,我可以用已有的东西实施它吗?

我已经查看了该帖子,网址为How to handle touch gestures in SwiftUI in Swift UIKit Map component?

Add single pin to Mapkit with SwiftUI

一旦有了坐标,放下销钉就很简单了,但是我无法把头放在获取坐标上。

谢谢。

mapkit swiftui mapkitannotation
1个回答
0
投票

没有MinimumDistance的DragGesture立即激活,并且在onChanged侦听器中具有location和startLocation,您可以使用它来获取位置,如下所示:

struct GesturesView: View {
    @State private var location: CGPoint = .zero

    var body: some View {
        let drag = DragGesture(minimumDistance: 0).onChanged { 
            self.location = $0.startLocation 
        }

        let longPress = LongPressGesture().onEnded { _ in
            self.doSomething(with: self.location)
        }

        let gesture = longPress.simultaneously(with: drag)

        return Rectangle()
            .frame(width: 300, height: 300)
            .padding()
            .gesture(gesture)
    }

    func doSomething(with location: CGPoint) {
        print("Pressed at", location)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.