ios - 无法在 MKAnnotationView 上转换子类

标签 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

}

但是我一直收到以下错误 MKAnnotationView 类型的值没有成员 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);

    }
}

最佳答案

你的第一行是

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
}

关于ios - 无法在 MKAnnotationView 上转换子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33341591/

相关文章:

ios - 如何在 UITableView 中动画更改顺序?

objective-c - 具有自定义字体的 UILabel 在 iOs 5 模拟器中不显示自定义字体

ios - 是否有使用 Fabric 在 iOS 上激活 Beta 测试人员的一步法?

ios - 更改 timeAgo 使系统过期

ios - 当选择 UIButton 时,文本标签上会出现一个白色框

ios - 为什么在呈现 View Controller 后 UIView 从层次结构中删除?

ios - SwiftDate - 迄今为止的字符串

objective-c - 如何正确地从另一个 viewController 中删除一个 pin

iphone - 处理 MKMapView 上的 MKAnnotations 时速度变慢

iphone - 尝试使用 didSelectAnnotationView 和 didDeselectAnnotationView 对 subview 进行动画处理