Без привязки к ObjectiveC, можем ли мы получить координаты касания только в SwiftUI? - PullRequest
0 голосов
/ 13 октября 2019

У меня есть следующий код:

    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)
            })

        }
    }

С чем я сталкиваюсь, так это с реализацией func convert(_ point: CGPoint, toCoordinateFrom view: UIView?) -> CLLocationCoordinate2D для получения широты жеста исключительно с использованием SwiftUI / Combine. Является ли это возможным? Если нет, могу ли я реализовать это с тем, что у меня есть?

Я рассмотрел сообщение на Как обрабатывать сенсорные жесты в SwiftUI в компоненте Swift UIKit Map?

и

Добавить один пин-кодв Mapkit с помощью SwiftUI

Как только у меня есть координаты, просто уронить булавку, но я не могу обернуться, чтобы получить координаты.

Спасибо.

1 Ответ

1 голос
/ 14 октября 2019

DragGesture без MinimumDistance активируется немедленно и имеет location и startLocation в слушателе onChanged, вы можете использовать его для захвата местоположения следующим образом:

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)
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...