无法在MKAnnotationView上转换子类

时间:2015-10-26 08:44:23

标签: ios swift mkannotation

我的FBSingleClusterView中有一个名为companyString的字符串。但是我似乎无法访问,因为MKAnnotationView不会更改为我的FBSingleClusterView

我的代码

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)  
    pinView = FBSingleClusterView(annotation: annotation, reuseIdentifier: reuseId) as FBSingleClusterView
    pinView.companyString = singleAnnotation.name

}

但是我不断收到错误value of type MKAnnotationView has no member companyString

为什么没有将它转换为FBSingleClusterView,它是MKAnnotationView的子类?

FBSingleClusterView

class FBSingleClusterView: MKAnnotationView {

    var bubbleView: BubbleView?
    var addressString: String?
    var companyString: String?
    var logoImage: UIImage?

    override init(annotation: MKAnnotation?, reuseIdentifier: String?){
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

        // change the size of the cluster image based on number of stories


        backgroundColor = UIColor.clearColor()
        setNeedsLayout()


    }

    required override init(frame: CGRect) {
        super.init(frame: frame)

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }


    override func layoutSubviews() {

        // Images are faster than using drawRect:

        centerOffset = CGPointMake(0, -image!.size.height/2);

    }
}

2 个答案:

答案 0 :(得分:2)

你的第一行是

var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)

因此,pinView现在是MKAnnotationView类型?

Why come it isn't being casted into a FBSingleClusterView, which is a subclass of the MKAnnotationView?

设置var类型后,您无法重新指定其他类型。

建议的解决方案是

if let pinView:FBSingleClusterView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? FBSingleClusterView
{
      pinView.companyString = singleAnnotation.name
}

答案 1 :(得分:0)

尝试这个(我在“测试”上替换了你的vars):

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    var pinView: FBSingleClusterView! = nil
    if let reuseView = mapView.dequeueReusableAnnotationViewWithIdentifier("test") as? FBSingleClusterView {
        pinView = reuseView
    } else {
        pinView = FBSingleClusterView(annotation: annotation, reuseIdentifier: "test")
    }
    pinView.companyString = "Test"
    return pinView
}

您的问题在于类型转换