【问题标题】:MKMapAnnotationView - how to support dark mode in SwiftMKPinAnnotationView - 如何在 Swift 中支持暗模式
【发布时间】:2020-07-08 22:47:26
【问题描述】:
我有 Apple 的 mapView 和其中显示的自定义标记。每个标记在资产中都有 2 个图像,用于适当的暗模式和亮模式。问题在于标记不会对暗/亮模式主题更改做出反应。我试过的:
- 在方法
traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)中重新加载mapView的输入视图
- 在方法
traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)内的标记视图类中重置图像
那么,当主题改变时如何更新标记?
【问题讨论】:
标签:
ios
swift
mkmapview
mkannotationview
apple-maps
【解决方案1】:
我刚刚发现了同样的事情,所以我修改了我的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
}
...