How to reposition compass of MKMapView?

前端 未结 3 1970
说谎
说谎 2021-01-19 10:38

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 NSClassFrom         


        
相关标签:
3条回答
  • 2021-01-19 10:47

    For iOS 11 and above, use MKCompassButton.

    let compass = MKCompassButton(mapView: mapView)
    
    0 讨论(0)
  • 2021-01-19 11:04

    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)
    }
    
    0 讨论(0)
  • 2021-01-19 11:05

    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)
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题