女朋友的一个项目里需要用到百度地图的标注功能,也就是大头针戳点,需要响应用户点击事件,但是代码看起来完全没问题,可是didSelectAnnotationView方法死活调用不到,然后我自己做的一个App里,也遇到了相同的问题,代理方法viewForAnnotation也是一直无法生效。找了很多博客都没发现正确的解决方法,最后自己找到了原因,是delegate的设置顺序错了,这个错误虽然不是什么大的bug,但是找起来也能累死人,分享给大家,避免这种低级错误
1.在地图类初始化之前就提早设置了代理
var mapView: MAMapView?
override func viewDidLoad() {
super.viewDidLoad()
//这一句是设置mapview的代理方法,但是此时我还没有初始化地图,initMapView()方法在下面才执行,所以相当于根本没设置代理
self.mapView?.delegate = self
// Do any additional setup after loading the view.
//去除navigationbar底部黑线
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationItem.title = "快递中心"
//初始化地图view
initMapView()
}
//初始化地图view
func initMapView() {
//在这里初始化了mapView
mapView = MAMapView(frame: mainView.bounds)
mapView!.delegate = self
mapView!.zoomLevel = 15
mapView!.showsUserLocation = true
mapView!.userTrackingMode = MAUserTrackingMode.None
mapView!.allowsBackgroundLocationUpdates = true
mapView!.pausesLocationUpdatesAutomatically = true
mapView!.distanceFilter = 10.0
mapView!.desiredAccuracy = kCLLocationAccuracyBestForNavigation
mapView!.setCenterCoordinate(CLLocationCoordinate2D.init(latitude: 22.347146, longitude: 113.533344), animated: true)
mainView.addSubview(mapView!)
}
var mapView: MAMapView?
override func viewDidLoad() {
super.viewDidLoad()
//这一句是设置mapview的代理方法,但是此时我还没有初始化地图,initMapView()方法在下面才执行,所以相当于根本没设置代理
self.mapView?.delegate = self
// Do any additional setup after loading the view.
//去除navigationbar底部黑线
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationItem.title = "快递中心"
//初始化地图view
initMapView()
}
//初始化地图view
func initMapView() {
//在这里初始化了mapView
mapView = MAMapView(frame: mainView.bounds)
mapView!.delegate = self
mapView!.zoomLevel = 15
mapView!.showsUserLocation = true
mapView!.userTrackingMode = MAUserTrackingMode.None
mapView!.allowsBackgroundLocationUpdates = true
mapView!.pausesLocationUpdatesAutomatically = true
mapView!.distanceFilter = 10.0
mapView!.desiredAccuracy = kCLLocationAccuracyBestForNavigation
mapView!.setCenterCoordinate(CLLocationCoordinate2D.init(latitude: 22.347146, longitude: 113.533344), animated: true)
mainView.addSubview(mapView!)
}