How to reposition compass of MKMapView?

前端 未结 3 1978
说谎
说谎 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 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)
            }
        }
    }
    

提交回复
热议问题