【问题标题】:Marking a location in a MKMapView在 MKMapView 中标记位置
【发布时间】:2014-01-25 15:31:51
【问题描述】:

我正在尝试在地图视图中标记一个位置。

首先我在像这样的一个单独的类中实现了MKAnnotation 协议。

AddressAnnotation.h

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface AddressAnnotation : NSObject <MKAnnotation>

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;

- (id)initWithCoordinates:(CLLocationCoordinate2D)location;

@end

AddressAnnotation.m

#import "AddressAnnotation.h"

@implementation AddressAnnotation

- (id)initWithCoordinates:(CLLocationCoordinate2D)location
{
    self = [super init];
    if (self)
    {
        self.coordinate = location;
    }

    return self;
}

@end

然后在视图控制器中,我实现了MKMapViewDelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MKUserLocation class]])
    {
        return nil;
    }

    static NSString *myIdentifier = @"myIndentifier";
    MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:myIdentifier];

    if (!pinView)
    {
        pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:myIdentifier];
        pinView.pinColor = MKPinAnnotationColorRed;
        pinView.animatesDrop = NO;
    }
    return pinView;
}

viewDidLoad 方法中,我初始化了AddressAnnotation 类的一个实例。

- (void)viewDidLoad
{
    [super viewDidLoad];

    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(34.421496, -119.70182);

    AddressAnnotation *pinAnnotation = [[AddressAnnotation alloc] initWithCoordinates:coordinate];
    [self.mapView addAnnotation:pinAnnotation];
}

但我不断收到以下错误。

-[AddressAnnotation setCoordinate:]:无法识别的选择器发送到实例

我不确定我在这里做错了什么。有人可以帮帮我吗?

谢谢。

【问题讨论】:

    标签: ios mkmapview mapkit mkannotation mkmapviewdelegate


    【解决方案1】:

    问题是您定义了一个只读坐标属性。因此,在尝试设置它时会出现异常。只需删除您的坐标属性定义,因为这已由 MKAnnotation 协议提供。

    【讨论】:

    • 我搞定了。谢谢。但屏幕上显示的区域不是标记区域。应用启动时如何关注 pin 所在的区域?
    • MKCoordinateRegion mapRegion; mapRegion.center = 坐标; mapRegion.span.latitudeDelta = 0.05; mapRegion.span.longitudeDelta = 0.05; [mapView setRegion:region Animation:YES]
    【解决方案2】:

    您的问题是 coordinate 属性是只读的。而且,它已经被MKAnnotation 协议定义了。

    当您实现协议定义 @properties 时,您实际上必须 @syntentize 这些属性以在您的类中创建一个支持实例变量 (ivar),或者,您必须为这些属性实现自定义 setter 和 getter。

    请记住:属性只不过是一个 setter 和 getter 方法,并且可以选择由 ivar 支持。由 ivar 支持是 @property 的默认行为。

    因此,简而言之,要解决您在AddressAnnotation.h 文件中的问题,请删除coordinate 属性并在AddressAnnotion.m 文件中添加:

    // after the line @implementation Address Annotation
    @syntetize coordinate = _coordinate;
    

    【讨论】:

    • 我不知道你为什么被否决但你是对的。这就是问题所在。谢谢,我设法纠正它。 :) 我不得不接受 rist 的回答,因为他先在这里发布,但感谢您的详细回答。
    • 不需要再合成属性了
    • 如果属性是在协议中定义的。事实上,如果你不这样做,你会收到 Xcode 的警告。
    猜你喜欢
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多