代码之家  ›  专栏  ›  技术社区  ›  mistakeNot

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

  •  4
  • mistakeNot  · 技术社区  · 8 年前

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

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

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

    3 回复  |  直到 8 年前
        1
  •  6
  •   mugx    8 年前

    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)
    }
    
        2
  •  1
  •   Kosuke Ogawa    8 年前

    对于iOS 11及以上版本,请使用 MKCompassButton .

    let compass = MKCompassButton(mapView: mapView)
    
        3
  •  1
  •   Kaiser Abliz    7 年前

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