【问题标题】:How to reposition compass of MKMapView?如何重新定位 MKMapView 的指南针?
【发布时间】:2019-07-12 23:06:41
【问题描述】:

我想移动 MKMapView 指南针。我想通过这样的方式获得它的参考:

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

但是编译器会抱怨“使用未声明的类型 'NSClassFromString'”。 如何修复此代码?

【问题讨论】:

    标签: ios swift mapkit mkmapview ios11


    【解决方案1】:

    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

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

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

    【讨论】:

    • 我试过了,但没用。我猜苹果只是出于某种原因不想让你触摸指南针:/
    • NSClassFromString 未被弃用。不是根据 Apple 的文档,也不是 Swift 和 Objective-C 的头文件。
    【解决方案2】:

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

    let compass = MKCompassButton(mapView: mapView)
    

    【讨论】:

      【解决方案3】:

      这是我通过子类化 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:$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)
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-12
        • 2014-04-25
        • 1970-01-01
        • 2013-10-05
        • 1970-01-01
        • 1970-01-01
        • 2011-07-02
        相关资源
        最近更新 更多