How to reposition compass of MKMapView?

怎甘沉沦 提交于 2019-12-04 04:11:33

问题


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?


回答1:


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



回答2:


For iOS 11 and above, use MKCompassButton.

let compass = MKCompassButton(mapView: mapView)



回答3:


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


来源:https://stackoverflow.com/questions/48343381/how-to-reposition-compass-of-mkmapview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!