perfectoitaliano
perfectoitaliano

Reputation: 1

SwiftUI - how can I have a long press gesture trigger an alert with text view and then drop an mkannotationpin with the text as it’s title?

very new to swiftUI but I couldn't find this answer anywhere. Thanks in advance.

At the end of a LongPressGesture, I have this gesture recogniser method called, which executes fine. The only problem is I want to call showAlert() and wait for the text entry which updates the annotationName variable. This is meant to be the title of my annotation pin.

The problem is the showAlert function and TextField only shows up when the handlePress function has completed. I have checked it in debugger. So the functionality of this code is such that parent.locationName is always the previous TextField entry.

I've looked into async functions but I'm not sure if that can be implemented with the gesture recogniser.

Essentially what I am intending is:

handlePress() calls showAlert() which executes before returning to the rest of handlePress()

At the moment it is:

handlePress() calls showAlert() however showAlert() executes at the end of handlePress (eg. the displaying of textEntry field appears after the annotation has been added)

  @objc func handlePress(gesture: UIGestureRecognizer) {
        
        // want this to run and show alert, which is a text entry and updates
        // parent.locationName
        showAlert(alert: alert())

        var annotationName = parent.locationName
                    
        if gesture.state == .ended {
            
            if let mapView = gesture.view as? MKMapView {
                let point = gesture.location(in: mapView)

                let coordinate = mapView.convert(point, toCoordinateFrom: mapView)
                let annotation = MKPointAnnotation()
                annotation.coordinate = coordinate

                annotation.title = annotationName
                mapView.addAnnotation(annotation)
                

            }
        }
        
    }

Upvotes: 0

Views: 1323

Answers (1)

dig
dig

Reputation: 255

Maybe you could use alert action callback

struct ContentView: View {

@State var showingAlert: Bool = false

func actionAfterAlert() {
    print("Action after press Ok")
}

var body: some View {
    VStack {
        Text("Hello, world!")
            .padding()
            .onLongPressGesture {
                showingAlert = true
            }
    }
    .alert(isPresented: $showingAlert) { () -> Alert in
                    Alert(title: Text("iOS Alert"), message: Text("Alert"), primaryButton: .default(Text("Ok"), action: {
                        actionAfterAlert()
                    }), secondaryButton: .default(Text("Dismiss")))
   
    }
}
}

Upvotes: 0

Related Questions