Get frame of annotation on map view
Asked Answered
T

2

9

In my app I have custom annotations where the leftCalloutAccessoryView is a circular UIView. This works perfectly in the simulator with this code:

    let rideTimeView = UIView()
    rideTimeView.frame = CGRectMake(5, 5, 50, 50)
    rideTimeView.layer.cornerRadius = 25

The problem arises when I run the app on actual devices. It works fine on (I believe) 6 and 6 Plus, but overlaps at the bottom on 4 and 5.

Is there any way I can get the dimensions of the annotation?

Truman answered 17/8, 2015 at 23:21 Comment(1)
Refer this: #11422232 Hope it helpsBushelman
C
2

Swift 3:

To get the frame of MKAnnotationView in MKMapView, first you will need a reference to the MKAnnotation. Then do:

if let annotationView = self.mapView.view(for: annotation) {
    let frameOfAnnotationViewInMapView = annotationView.frame
}

In addition, if you want the frame of the MKAnnotationView on screen, do:

let frameOfViewInSuperview = self.mapView.convert(frameOfAnnotationViewInMapView, to: self.mapView.superview?.superview?.superview?.superview?.superview?.superview?.superview?.superview?.superview?.superview?.superview?.superview?.superview?.superview?.superview)

The number of times you need to call .superview will depend on how deep your MKMapView is nested. For my case, it was nested very deep.

Catenate answered 3/2, 2017 at 0:13 Comment(0)
P
0

You can convert frame from superview to window:

let frame = convertRect(rideTimeView.frame, toView: UIApplication.sharedApplication().delegate!.window!)
Palmerpalmerston answered 20/8, 2015 at 10:42 Comment(6)
I've tried doing this - let frame = pinView.convertRect(pinView.frame, toView: UIApplication.sharedApplication().delegate!.window!). pinView is the annotation that I need the frame for, but it just returns (0,0,0,0).Truman
Try to use pinView.superview.convertRect. Let me know if it helps.Palmerpalmerston
Didn't work unfortunately. I should mention that the above code is within viewForAnnotation, so at that point would pinView actually have a frame?Truman
What does debugger show you when you write "po pinView" and "po pinView.superview"?Palmerpalmerston
I get (0,0,0,0) with pinView, and the app just crashes with nil when I try pinView.superview!.Truman
Did you try to debug view using button on debug panel? Or try to debug view by showing colored frames of each view element?Palmerpalmerston

© 2022 - 2024 — McMap. All rights reserved.