Search code examples
iosswiftmkannotation

Cant cast subclass on MKAnnotationView


I'm having a string in my FBSingleClusterView called companyString. However i can't seem to access because the MKAnnotationView won't be changed to my FBSingleClusterView?

My Code

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

}

However i keep getting following error value of type MKAnnotationView has no member companyString.

Why come it isn't being casted into a FBSingleClusterView, which is a subclass of the 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);

    }
}

Solution

  • Your first line is

    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
    

    As such, pinView is now type MKAnnotationView?

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

    Once a var type is set, you cannot reassign another type.

    Suggested solution would be

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