Custom font for MKAnnotationView Callout

后端 未结 2 754
天涯浪人
天涯浪人 2021-01-20 16:22

Fortunately, the standard callout view for an MKAnnotationView meets our needs - title, subtitle, leftCalloutAccessoryView

2条回答
  •  走了就别回头了
    2021-01-20 17:11

    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
        }
      }
    }
    

提交回复
热议问题