4

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 NSClassFromString("MKCompassView")}

However the compiler complains " Use of undeclared type 'NSClassFromString' ". How can I fix this code?

mugx
  • 9,869
  • 3
  • 43
  • 55
mistakeNot
  • 743
  • 2
  • 10
  • 24

3 Answers3

6

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)
}
mugx
  • 9,869
  • 3
  • 43
  • 55
  • i tried but it didn't work. I guess apple just doesnt want you touching the compass for some reason :/ – mistakeNot Jan 19 '18 at 19:19
  • NSClassFromString is not deprecated. Not according to Apple's documentation nor in the header files for both Swift and Objective-C. – I make my mark Jul 16 '18 at 09:48
1

For iOS 11 and above, use MKCompassButton.

let compass = MKCompassButton(mapView: mapView)
Kosuke Ogawa
  • 7,383
  • 3
  • 31
  • 52
1

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)
        }
    }
}
Kaiser Abliz
  • 153
  • 2
  • 7