Fortunately, the standard callout view for an MKAnnotationView
meets our needs - title
, subtitle
, leftCalloutAccessoryView
Since I needed the Swift version - here it is. Also, you have to call setNeedsLayout() on didAddSubview() because otherwise when you deselect and reselect the annotation layoutSubviews() is not called and the callout has its old font.
// elsewhere, in a category on UIView.
// thanks to this answer: http://stackoverflow.com/a/25877372/607876
typealias ViewBlock = (_ view: UIView) -> Bool
extension UIView {
func loopViewHierarchy(block: ViewBlock?) {
if block?(self) ?? true {
for subview in subviews {
subview.loopViewHierarchy(block: block)
}
}
}
}
// then, in your MKAnnotationView subclass
class CustomFontAnnotationView: MKAnnotationView {
override func didAddSubview(_ subview: UIView) {
if isSelected {
setNeedsLayout()
}
}
override func layoutSubviews() {
// MKAnnotationViews only have subviews if they've been selected.
// short-circuit if there's nothing to loop over
if !isSelected {
return
}
loopViewHierarchy { (view: UIView) -> Bool in
if let label = view as? UILabel {
label.font = labelFont
return false
}
return true
}
}
}