如何重新定位MKMapView的指南针?

时间:2018-01-19 14:33:37

标签: ios swift mapkit mkmapview ios11

我想移动MKMapView指南针。我希望通过以下方式获得它的参考:

let compassView = mapView.subviews.filter {$0 is NSClassFromString("MKCompassView")}

然而,编译器抱怨“使用未声明的类型'NSClassFromString'”。 我该如何修复此代码?

3 个答案:

答案 0 :(得分:5)

iOS 11

你应该使用MKCompassButton,解释新内容的文档: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

您可以尝试使用String(describing:),例如:

if let compassButton = (mapView.subviews.filter { String(describing:$0).contains("MKCompassView") }.first) {
   print(compassButton)
}

答案 1 :(得分:1)

对于iOS 11及更高版本,请使用MKCompassButton

let compass = MKCompassButton(mapView: mapView)

答案 2 :(得分:0)

这是我通过子类化MKMapView重新定位指南针视图的解决方案。
代码已在iOS10及更高版本上经过Swift 5.0测试。
注意:在iOS10设备上进行测试时,必须旋转地图以使指南针可见。

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