我对于MKAnnotationView有2个图像状态,分别是selected
和deselected
。问题在于这两个状态之间的转换很差。网上没有太多关于此的内容,通常我在过渡方面遇到麻烦。
这里是我正在使用的MKAnnotationView
:
class CustomPinView: MKAnnotationView {
func updateImage() {
guard let mapAnnotation = annotation as? MapAnnotation else {return}
if let selectedImageName = mapAnnotation.selectedImageName, isSelected {
image = UIImage(inCurrentBundleWithName: selectedImageName)
} else if let imageName = mapAnnotation.imageName {
image = UIImage(inCurrentBundleWithName: imageName)
} else {
image = nil
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
updateImage()
}
override var annotation: MKAnnotation? {
didSet {
updateImage()
}
}
}
我更新了updateImage
函数,使其看起来像这样:
private func updateImage() {
CATransaction.begin()
CATransaction.setAnimationDuration(0.2)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: .easeOut))
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseIn, animations: {
guard let mapAnnotation = self.annotation as? MapAnnotation else {return}
if let selectedImageName = mapAnnotation.selectedImageName, self.isSelected {
self.image = UIImage(inCurrentBundleWithName: selectedImageName)
self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.6)
} else if let imageName = mapAnnotation.imageName {
self.image = UIImage(inCurrentBundleWithName: imageName)
self.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
} else {
self.image = nil
}
self.centerOffset = CGPoint(x: 0.5, y: 0.5)
}, completion: nil)
CATransaction.commit()
}
这是从此答案中摘录的:https://stackoverflow.com/a/54431257/4114335