首页 > 解决方案 > 我想在集群中加载 XIB 或 View 而不是 Apple Maps 中的图像

问题描述

我正在使用此代码创建一个集群,我正在获取带有数字的圆形图像。我想在集群视图而不是图像中加载 XIB。

我创建了一个名为 image() 的函数来创建带有数字的图像,但我需要显示一个视图。

这是我为此使用的两个类。

class UserAnnotationView: MKAnnotationView {

static let preferredClusteringIdentifier = Bundle.main.bundleIdentifier! + ".UserAnnotationView"

override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
    super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
    clusteringIdentifier = UserAnnotationView.preferredClusteringIdentifier
    image = UIImage(named: "marker_default_yellow")
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override var annotation: MKAnnotation? {
    willSet {
        clusteringIdentifier = UserAnnotationView.preferredClusteringIdentifier
    }
}
}

//MARK:- Clustering
class UserClusterAnnotationView: MKAnnotationView {
static let preferredClusteringIdentifier = Bundle.main.bundleIdentifier! + ".UserClusterAnnotationView"

override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
    super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
    collisionMode = .circle
    updateImage()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override var annotation: MKAnnotation? { didSet { updateImage() } }

private func updateImage() {
    if let clusterAnnotation = annotation as? MKClusterAnnotation {
        self.image = image(count: clusterAnnotation.memberAnnotations.count)
    } else {
        self.image = UIImage(named: "marker_default_yellow")//image(count: 1)
    }
}

func image(count: Int) -> UIImage {
    let bounds = CGRect(origin: .zero, size: CGSize(width: 45, height: 45))
    
    let renderer = UIGraphicsImageRenderer(bounds: bounds)
    return renderer.image { _ in
        // Fill full circle with tricycle color
        UIColor.white.setFill()
        UIBezierPath(ovalIn: bounds).fill()
        
        // Fill inner circle with white color
        kAppDefaultColor.setFill()
        UIBezierPath(ovalIn: bounds.insetBy(dx: 1, dy: 1)).fill()
        
        // Finally draw count text vertically and horizontally centered
        let attributes: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor.white,
            .font: UIFont(name: Constants.FontName.rubikRegular, size: 18) ?? UIFont()
        ]
        
        let text = "\(count)"
        let size = text.size(withAttributes: attributes)
        let origin = CGPoint(x: bounds.midX - size.width / 2, y: bounds.midY - size.height / 2)
        let rect = CGRect(origin: origin, size: size)
        text.draw(in: rect, withAttributes: attributes)
    }
}
}

标签: iosswiftiphonemapkit

解决方案


推荐阅读