iOS 高德地图自定义气泡处理


此文讲的是使用高德地图自定义气泡,并且点击自定义气泡后对应的 MAMapView 地图对象能够接收到点击的通知事件 didAnnotationViewCalloutTapped,气泡也在点击后被移除。

效果:


iOS 高德地图自定义气泡处理_第1张图片
自定义气泡.gif

添加自定义气泡
  1. 定义弹出的气泡视图对象:

    import UIKit
    
    // MARK: - 外部接口
    extension XQStationCalloutView {
     
        /// 设置场站数据
        ///
        /// - parameter station: 场站模型
        public func setStation(station: XQStationModel) {
            textLabel.text = station.name
            distanceLabel.text = "\(station.distance)km"
        }
    }
    
    // MARK: - 事件响应
    extension XQStationCalloutView {
        
    }
    
    public class XQStationCalloutView: UIButton {
     
        // MARK: - 生命周期
     
        public required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setupParameter()
            setupUI()
            layoutPageSubviews()
        }
     
        public override init(frame: CGRect) {
            super.init(frame: frame)
            setupParameter()
            setupUI()
            layoutPageSubviews()
        }
     
        // MARK: - 界面初始化
     
        /// 初始化参数
        public func setupParameter() {
         
        }
     
        /// 初始化UI
        public func setupUI() {
            distanceLabel.text = "1.54km"
            navigationItem.addSubview(distanceLabel)
            textLabel.text = "深圳宝安区华美在要在要在要在要"
            contentItem.addSubview(textLabel)
            addSubview(navigationItem)
            addSubview(contentItem)
            addSubview(entryItem)
        }
     
        /// 初始化布局
        public func layoutPageSubviews() {
            distanceLabel.snp.makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.bottom.equalToSuperview().offset(-14)
            }
            textLabel.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(8)
                make.right.equalToSuperview().offset(-12)
                make.bottom.equalTo(self.snp.centerY).offset(-3)
            }
            navigationItem.snp.makeConstraints { (make) in
                make.left.centerY.equalToSuperview()
            }
            entryItem.snp.makeConstraints { (make) in
                make.centerY.right.equalToSuperview()
            }
            contentItem.snp.makeConstraints { (make) in
                make.centerY.equalToSuperview()
                make.left.equalTo(navigationItem.snp.right)
                make.right.equalTo(entryItem.snp.left)
            }
        }
     
        // MARK: - 内部接口
     
        // MARK: - 公共成员变量
     
        // MARK: - 私有成员变量
     
        // MARK: - 子控件
     
        /// 左侧导航图标
        fileprivate let navigationItem = UIImageView(image: UIImage(named: "icon_info_btn1"))
     
        /// 中间内容图标
        fileprivate let contentItem = UIImageView(image: UIImage(named: "icon_info_btn2"))
     
        /// 右侧箭头图标
        fileprivate let entryItem = UIImageView(image: UIImage(named: "icon_info_btn3"))
     
        /// 距离文本标签
        fileprivate let distanceLabel: UILabel = {
            let label = UILabel()
            label.textColor = .white
            label.font = UIFont.boldSystemFont(ofSize: 10)
            return label
        }()
     
        /// 场站名称文本标签
        fileprivate let textLabel: UILabel = {
            let label = UILabel()
            label.textColor = UIColor(hex: "#1f97b7")
            label.font = UIFont.boldSystemFont(ofSize: 14)
            return label
        }()
    }
    
  2. 定义弹出自定义气泡的标注视图对象:

    1. 上面将气泡定义为 UIButton,但是点击后并无法正常地调用响应函数:

      这是因为自定义的气泡是添加到大头针上的,而大头针的 size 只有下面很小一部分,所以按钮是在大头针的外面的,而 iOS 按钮超过父视图范围是无法响应事件的处理方法。可以通过重写标注视图类的 hitTest 函数来修复这问题:

     /// 因为添加的气泡是在标注视图范围之外,所以重写点击测试,让按钮的点击事件能够得到响应
     public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
         
         if let view = super.hitTest(point, with: event) {
             return view
         }
         
         guard let calloutView = calloutView else {
             return nil
         }
         
         let local = calloutView.convert(point, from: self)
         return calloutView.bounds.contains(local) ? calloutView : nil
     }
    
    1. 通过上面重写 hitTest 修复气泡的点击问题,但这时即使点击了气泡 MAMapView 对象也无法调用相应的代理方法:

      可以将 MAMapView 对象传给标注类,在按钮的点击事件中调用对应的代理方法:

      /// 气泡点击处理
      public func calloutClickHandle() {
         // 获取当前地图控件
         guard let mapView = mapView else { return }
         // 调用地图控件气泡的点击事件回调处理
         mapView.delegate.mapView?(mapView, didAnnotationViewCalloutTapped: self)
      }
      
    2. 继续添加气泡的点击移除功能,如果只是调用气泡视图的 removeFromSuperview 方法,这样可以将气泡移除,但下次再点击该标注时则无法弹出气泡:

      因为 MAMapView 仍然以为该标注已经被选中了,所以在移除气泡的同时告诉 MAMapView 取消该标注的选中状态:

      /// 气泡点击处理
      public func calloutClickHandle() {
         // 获取当前地图控件,并判断当前是否有选中的标注
         guard let mapView = mapView, mapView.selectedAnnotations.count > 0 else { return }
         // 获取当前选中标注对象模型 MAAnnotation
         let annotation = mapView.selectedAnnotations[0] as? MAAnnotation
         // 取消选中的标注对象的选中状态,这个接口内部会调用 setSelected 方法
         mapView.deselectAnnotation(annotation, animated: false)
         // 调用地图控件气泡的点击事件回调处理
         mapView.delegate.mapView?(mapView, didAnnotationViewCalloutTapped: self)
      }
      

以下为标注视图的完整代码:

import UIKit

// MARK: - 外部接口
extension XQPointAnnotationView {
    
}

// MARK: - 事件响应
extension XQPointAnnotationView {
    
    /// 气泡点击处理
    public func calloutClickHandle() {
        // 获取当前地图控件,并判断当前是否有选中的标注
        guard let mapView = mapView, mapView.selectedAnnotations.count > 0 else { return }
        // 获取当前选中标注对象模型 MAAnnotation
        let annotation = mapView.selectedAnnotations[0] as? MAAnnotation
        // 取消选中的标注对象的选中状态
        mapView.deselectAnnotation(annotation, animated: false)
        // 调用地图控件气泡的点击事件回调处理
        mapView.delegate.mapView?(mapView, didAnnotationViewCalloutTapped: self)
    }
    
}

/// 自定义标注图
public class XQPointAnnotationView: MAAnnotationView {
    
    /// 标注所在地图对象,用来当点击自定义气泡后回调相应的代理
    public var mapView: MAMapView?
    
    /// 自定义的气泡视图
    fileprivate var calloutView: XQStationCalloutView?
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        canShowCallout = false
    }
    
    public override init!(annotation: MAAnnotation!, reuseIdentifier: String!) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
        canShowCallout = false
    }
    
    public override func setSelected(_ selected: Bool, animated: Bool) {
        guard self.isSelected != selected else { return }
        if selected {
            calloutView = XQStationCalloutView(frame: CGRect(x: 0, y: 0, width: 230, height: 60))
            calloutView!.center = CGPoint(x: bounds.midX + 8, y: -bounds.midY - 8)
            calloutView!.addTarget(self, action: #selector(self.calloutClickHandle), for: .touchUpInside)
            addSubview(calloutView!)
        } else {
            removeCalloutView()
        }
        super.setSelected(selected, animated: animated)
    }
    
    /// 因为添加的气泡是在标注视图范围之外,所以重写点击测试,让按钮的点击事件能够得到响应
    public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        
        if let view = super.hitTest(point, with: event) {
            return view
        }
        
        guard let calloutView = calloutView else {
            return nil
        }
        
        let local = calloutView.convert(point, from: self)
        return calloutView.bounds.contains(local) ? calloutView : nil
    }
    
    /// 移除自定义气泡
    fileprivate func removeCalloutView() {
        calloutView?.removeFromSuperview()
        calloutView = nil
    }
}

你可能感兴趣的:(iOS 高德地图自定义气泡处理)