我在其中显示了Apple的mapView
和自定义标记。每个标记在素材资源中都有2张图像,分别用于暗和亮模式。问题在于标记对暗/亮模式主题更改没有反应。我尝试过的:
traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
中重新加载mapView的输入视图traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
内的标记视图类中重置图像那么,主题更改后如何更新标记?
答案 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
}
...