如何在MapKit中让指定标注置于其他周边标注之上?
地图标注无法置顶的解决方案
问题描述
地图上有30个位置十分接近的标注,需要实现点击按钮时,指定标注缩放并显示在所有周边标注上方。目前缩放功能已实现,但调用mapView.bringSubviewToFront(selectedAnnotationView)无法让标注置于上层。相关代码如下:
public func scaleAnnotation(_ annotation: BMAnnotation, selectedScale: CGFloat = 1.5) { let selectedAnnotation = mapView.annotations.last(where: { $0.coordinate == annotation.coordinate }) if let selectedAnnotation = selectedAnnotation, let selectedAnnotationView = mapView.view(for: selectedAnnotation) , selectedAnnotationView != lastSelectedAnnotationView { resetAnnotationScaling() let transform = CGAffineTransform(scaleX: selectedScale, y: selectedScale) UIView.animate(withDuration: 0.2) { selectedAnnotationView.transform = transform } // move selected annotation view to top // selectedAnnotationView.layer.anchorPointZ = CGFloat(Float.greatestFiniteMagnitude) mapView.bringSubviewToFront(selectedAnnotationView) lastSelectedAnnotationView = selectedAnnotationView } else { print("💥 - can't find location") } }
解决方法
1. 找到标注视图的实际父容器
很多地图SDK(比如百度地图)会把标注视图放在专门的容器视图中,而非直接作为mapView的子视图。此时调用mapView.bringSubviewToFront不会生效,需要找到标注视图的父容器后再调整层级:
// 替换原有的mapView.bringSubviewToFront(selectedAnnotationView) var parentContainer = selectedAnnotationView.superview // 遍历找到百度地图的标注容器BMKAnnotationContainerView while parentContainer != nil && !(parentContainer is BMKAnnotationContainerView) { parentContainer = parentContainer?.superview } // 调用父容器的bringSubviewToFront parentContainer?.bringSubviewToFront(selectedAnnotationView)
2. 利用标注视图的zIndex属性
如果使用的地图SDK支持标注视图的zIndex属性(百度地图BMKAnnotationView支持),可以通过设置更高的zIndex值让标注置顶:
// 给选中的标注设置最高层级 selectedAnnotationView.zIndex = Int.max // 重置其他标注的层级为默认值 for anno in mapView.annotations { guard let annoView = mapView.view(for: anno), annoView != selectedAnnotationView else { continue } annoView.zIndex = 0 // 这里替换为你的默认zIndex值 }
3. 调整层级操作的时机
动画可能会干扰层级调整,可以将层级操作放在动画完成的回调中:
UIView.animate(withDuration: 0.2) { selectedAnnotationView.transform = transform } completion: { _ in // 这里执行层级调整操作 var parentContainer = selectedAnnotationView.superview while parentContainer != nil && !(parentContainer is BMKAnnotationContainerView) { parentContainer = parentContainer?.superview } parentContainer?.bringSubviewToFront(selectedAnnotationView) }
内容的提问来源于stack exchange,提问作者Mahmoud Abdelwahab
相关产品推荐
相关产品推荐

