在 Swift 中创建动态 MKAnnotationView

Mih*_*ado 1 mapkit mkannotation mkannotationview ios9

目前,我知道如何使用静态引脚(添加的图像)创建 MKAnnotationView。

有谁知道或有任何资源,如何创建一个可以改变颜色的图钉,或者在其中显示一个数字,该数字会根据有关业务的信息而变化?

例如,我希望在营业结束时将图钉显示为红色,在营业时将图钉显示为绿色。甚至可能在图钉内有一个美元符号来告诉用户它有多贵。

编辑

我创建了一个名为CustomPin采用该MKAnnotation协议的类。此外,我不希望有一个MKAnnotationView可以更改的自定义图像。这是否意味着我必须MKAnnotationView在数组中添加多个图像,并在每次有关业务的详细信息发生变化时更改图像?

先感谢您!

deo*_*hal 5

您可以MKAnnotationView通过简单的继承来创建自定义。您可以使用此类从委托方法创建注释视图。

这是一个例子。

class KDAnnotationView: MKAnnotationView {

    let titleLabel = UILabel()

    convenience init(annotation: MKAnnotation?) {
        self.init(annotation: annotation, reuseIdentifier: "indetifier")
        self.canShowCallout = false
        self.frame = CGRectMake(0, 0, 75.0, 85.0)
        self.backgroundColor = UIColor.clearColor()
        self.centerOffset = CGPointMake(0, 0)

        self.titleLabel.backgroundColor = UIColor.clearColor()
        self.titleLabel.textColor = UIColor.blackColor()
        self.titleLabel.font = UIFont.systemFontOfSize(16.0)
        self.addSubview(self.titleLabel)
    }


    override func layoutSubviews() {
        super.layoutSubviews()

        var frame = CGRectInset(self.bounds, 5.0, 5.0)
            frame.size.height = 20.0
        self.titleLabel.frame = frame
    }


    override func drawRect(rect: CGRect) {
        super.drawRect(rect)


        let path = UIBezierPath()
        path.moveToPoint(CGPoint(x: CGRectGetMinX(rect), y: CGRectGetMinY(rect)))
        path.addLineToPoint(CGPoint(x: CGRectGetMaxX(rect), y: CGRectGetMinY(rect)))
        path.addLineToPoint(CGPoint(x: CGRectGetMaxX(rect), y: CGRectGetMaxY(rect) - 10.0))
        path.addLineToPoint(CGPoint(x: CGRectGetMidX(rect) + 5.0, y: CGRectGetMaxY(rect) - 10.0))
        path.addLineToPoint(CGPoint(x: CGRectGetMidX(rect), y: CGRectGetMaxY(rect)))
        path.addLineToPoint(CGPoint(x: CGRectGetMidX(rect) - 5.0, y: CGRectGetMaxY(rect) - 10.0))
        path.addLineToPoint(CGPoint(x: CGRectGetMinX(rect), y: CGRectGetMaxY(rect) - 10.0))
        path.closePath()
        UIColor.lightGrayColor().setStroke()
        UIColor.whiteColor().setFill()
        path.stroke()
        path.fill()

    }


    //MARK: - Public Methods
    func setText(text:String) {
        self.titleLabel.text = text
    }
}
Run Code Online (Sandbox Code Playgroud)