I want to move the MKMapView compass. I wanted to get a reference for it by something like this:
let compassView = mapView.subviews.filter {$0 is NSClassFrom
For iOS 11 and above, use MKCompassButton
.
let compass = MKCompassButton(mapView: mapView)
iOS 11
you should use MKCompassButton
, doc explaining the new stuff: WWDC 2017 new MapKit presentation.
let compassButton = MKCompassButton(mapView:mapView)
compassButton.frame.origin = CGPoint(x: 20, y: 20)
compassButton.compassVisibility = .visible
view.addSubview(compassButton)
iOS < 11
You might try to use String(describing:)
, something like:
if let compassButton = (mapView.subviews.filter { String(describing:$0).contains("MKCompassView") }.first) {
print(compassButton)
}
This is my solution for repositioning the compass view by subclassing MKMapView.
The code is Swift 5.0 tested on iOS10 and above.
Note: When you test this on iOS10 devices you have to rotate the map in order to make compass visible.
import MapKit
class MapView: MKMapView {
override func layoutSubviews() {
super.layoutSubviews()
if #available(iOS 10.0, *) {
self.showsCompass = true //*** - You have to set this true here, it does not work if you set it on storyboards or in a View Controller - ***
if let compassButton = (self.subviews.filter { String(describing:$0).contains("MKCompassView") }.first) {
compassButton.frame = CGRect(x: 20, y: 40, width: 36, height: 36)
}
} else {
let compassButton = MKCompassButton(mapView:self)
compassButton.frame.origin = CGPoint(x: 20, y: 40)
compassButton.compassVisibility = .visible
self.addSubview(compassButton)
}
}
}