尝试初始化annotationView时出现问题

时间:2014-09-25 08:25:28

标签: swift mkannotationview self

我想将用Obj-C编写的自定义MKAnnotationView转换为Swift,当我想要initWithAnnotation时出错。

下面我将提供ObjC和Swift代码:

class JPThumbnailAnnotationView: MKAnnotationView,JPThumbnailAnnotationViewProtocol {


var coordinate :CLLocationCoordinate2D
var imageView : UIImageView
var titleLabel : UILabel
var subtitleLabel : UILabel
var disclosureBlock : JPThumbnail.SequencerNext

func initWithAnnotation(annotation : MKAnnotation) {

    self = MKAnnotationView(annotation: annotation, reuseIdentifier: kJPSThumbnailAnnotationViewReuseID) //HERE IS WHERE I GET THE ERROR

        self.canShowCallout = true
        self.frame = CGRectMake(0, 0, kJPSThumbnailAnnotationViewStandardWidth, kJPSThumbnailAnnotationViewStandardHeight)
        self.centerOffset = CGPointMake(0, -kJPSThumbnailAnnotationViewVerticalOffset)


}

Objective-C版本是

- (id)initWithAnnotation:(id<MKAnnotation>)annotation {
  self = [super initWithAnnotation:annotation reuseIdentifier:kJPSThumbnailAnnotationViewReuseID];

  if (self) {
    self.canShowCallout = NO;
    self.frame = CGRectMake(0, 0, kJPSThumbnailAnnotationViewStandardWidth, kJPSThumbnailAnnotationViewStandardHeight);
    self.backgroundColor = [UIColor clearColor];
    self.centerOffset = CGPointMake(0, -kJPSThumbnailAnnotationViewVerticalOffset);

    _state = JPSThumbnailAnnotationViewStateCollapsed;

    [self setupView];
}

return self;

}

我得到的错误是:Can not assign self in a method

有没有一种方法我仍然可以在我的情况下分配self或者我应该只创建一个MKAnnotationView类型的变量将它分配给初始化器的结果并更改函数的返回类型或者是否有另一种方法可以执行此操作?

1 个答案:

答案 0 :(得分:0)

你在init方法中做错了,你应该像这样调用超类初始化器,

func initWithAnnotation(annotation : MKAnnotation) {

   super.init(annotation: annotation, reuseIdentifier: kJPSThumbnailAnnotationViewReuseID) //HERE IS WHERE I GET THE ERROR
   self.canShowCallout = true
   self.frame = CGRectMake(0, 0, kJPSThumbnailAnnotationViewStandardWidth, kJPSThumbnailAnnotationViewStandardHeight)
   self.centerOffset = CGPointMake(0, -kJPSThumbnailAnnotationViewVerticalOffset)
}