如何重新定位 MKMapView 的指南针?
How to reposition compass of MKMapView?
我想移动MKMapView的指南针。我想通过这样的方式获得参考:
let compassView = mapView.subviews.filter {[=10=] is NSClassFromString("MKCompassView")}
但是编译器抱怨“使用未声明的类型 'NSClassFromString'”。
我该如何修复此代码?
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:[=11=]).contains("MKCompassView") }.first) {
print(compassButton)
}
对于 iOS 11 及以上,使用 MKCompassButton
。
let compass = MKCompassButton(mapView: mapView)
这是我通过继承 MKMapView 来重新定位罗盘视图的解决方案。
代码是 Swift 5.0 在 iOS10 及更高版本上测试的。
注意:当您在 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:[=10=]).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)
}
}
}
我想移动MKMapView的指南针。我想通过这样的方式获得参考:
let compassView = mapView.subviews.filter {[=10=] is NSClassFromString("MKCompassView")}
但是编译器抱怨“使用未声明的类型 'NSClassFromString'”。 我该如何修复此代码?
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:[=11=]).contains("MKCompassView") }.first) {
print(compassButton)
}
对于 iOS 11 及以上,使用 MKCompassButton
。
let compass = MKCompassButton(mapView: mapView)
这是我通过继承 MKMapView 来重新定位罗盘视图的解决方案。
代码是 Swift 5.0 在 iOS10 及更高版本上测试的。
注意:当您在 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:[=10=]).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)
}
}
}