6

I am coding one Location based App by Swift.

I make my MapView can show Compass, but I would like to change the compass location from the right-up corner to the left-down corner.

Does any expert know how to move it?

Thank you in advanced.

Kevin
  • 711
  • 7
  • 19

2 Answers2

25

You can do this by setting the compass visibility to false and then adding a new compass

mapView.showsCompass = false

let compassBtn = MKCompassButton(mapView:mapView)
compassBtn.frame.origin = CGPoint(x: self.view.frame.maxX - 40, y: 20)
compassBtn.compassVisibility = .adaptive
view.addSubview(compassBtn)

You can use adaptive visibility so your new compass will behave like the original one.

Wesley Skeen
  • 1,164
  • 3
  • 14
  • 22
9

You can try to change this:

mapView.layoutMargins 

Or subclass the MKMapView component:

import MapKit

class MyMapView: MKMapView {    
    override func layoutSubviews() {
        super.layoutSubviews()

        if let compassView = self.subviews.filter({ $0.isKindOfClass(NSClassFromString("MKCompassView")!) }).first {
            compassView.frame = CGRectMake(15, 30, 36, 36)
        }
    }
}
G. Veronika
  • 232
  • 2
  • 11
  • Can you verify if the second method still works? I cannot find any view with class `MKCompassView` in the subviews of my instance of MKMapView. The compass is enabled and showing but inaccessible. – Ben Ong Jun 29 '17 at 09:58
  • @Ben-Ong The MKCompassView is definitely still a subview of MKMapView, though it's only in the hierarchy when the map is rotated and the compass is shown. I just checked against iOS 9.1 in the simulator, using XCode's "Debug View Hierarchy". – Taryn Sep 29 '17 at 01:31
  • Can someone verify this approach works and passes Apple's review? There's no doc on `MKCompassView`, and `MKCompassButton` is only available publicly starting iOS 11. This screams private API access to me. – nekonari Apr 04 '18 at 22:37
  • 3
    Confirmed that: `mapView.layoutMargins = view.safeAreaInsets` worked best for me. – ciauri Apr 07 '18 at 14:37
  • 1
    This also works fine: ```mapView.layoutMargins = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 8)``` – Serj Rubens Apr 18 '20 at 12:27