按下 mapView 的罗盘按钮时如何调用函数

How to call a function when the Compass Button of a mapView is pressed

我开发了一个应用程序,显示带有罗盘按钮的地图视图。按下此罗盘按钮时的自然功能是地图指向北方。 现在我想在按下这个罗盘按钮时调用一个函数。

可以在那里找到带有地图的应用程序视图(右上角可以看到罗盘按钮)

http://aceingolf.com/wp-content/uploads/2018/12/0.jpg

下面的代码运行良好。它只是为了提供一个完整的视图。

@IBOutlet weak var mapView: MKMapView!

let compassButton = MKCompassButton(mapView: mapView)   
compassButton.compassVisibility = .visible       
mapView.addSubview(compassButton)

我正在寻找一种方法来在用户按下地图视图上的罗盘按钮时创建一个动作。

我相信 MKCompassButton 继承自 UIView,因此您只需将 UITapGestureRecognizer 添加到 compassButton 即可,操作如下:

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleCompassTap))
    compassButton.addGestureRecognizer(tapGestureRecognizer)


    @objc func handleCompassTap() {
    // Implement your feature when the compass button tapped.
    }

取emrepuns代码

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleCompassTap))
compassButton.addGestureRecognizer(tapGestureRecognizer)


@objc func handleCompassTap() {
// Implement your feature when the compass button tapped.
}

并添加这一行

tapGestureRecognizer.numberOfTouchesRequired = 1

tapGestureRecognizer.numberOfTapsRequired = 1