MKMapAnnotationView-如何在Swift中支持暗模式

时间:2020-03-28 08:19:50

标签: ios swift mkmapview mkannotationview apple-maps

我在其中显示了Apple的mapView和自定义标记。每个标记在素材资源中都有2张图像,分别用于暗和亮模式。问题在于标记对暗/亮模式主题更改没有反应。我尝试过的:

  • 在方法traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)中重新加载mapView的输入视图
  • 在方法traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)内的标记视图类中重置图像

那么,主题更改后如何更新标记?

1 个答案:

答案 0 :(得分:2)

我刚刚发现了相同的东西,因此我修改了MKAnnotationView派生类来处理它:

class MapPinView: MKAnnotationView {
    
    // MKAnnotationView doesn't seem to automatically use the correct image for dark mode, so we have to ensure it does
    var combinedImage: UIImage? {
        didSet {
            updateImage()
        }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        if let imageName = selected ? "pushPinSelected" : "pushPin",
            let image = UIImage(named: imageName) {
            self.combinedImage = image
        }
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        if traitCollection.userInterfaceStyle != previousTraitCollection?.userInterfaceStyle {
            updateImage()
        }
    }
    
    private func updateImage() {
        image = combinedImage?.imageAsset?.image(with: traitCollection) ?? combinedImage
        if let image = self.image {
            centerOffset = CGPoint(x: 0.0, y: -image.size.height / 2.0)
        }
    }

}

请注意,在创建MapPinView时,我还初始化了combinedImage

extension MapView: MKMapViewDelegate {
    
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {    
        let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: Constants.annotationId, for: annotation) as! MapPinView
        annotationView.combinedImage = UIImage(named: "pushPin")            
        return annotationView
    }
...