Ios 在MKMapView中标记位置
我正试图在地图视图中标记一个位置 首先,我在这样一个单独的类中实现了Ios 在MKMapView中标记位置,ios,mkmapview,mapkit,mkannotation,mkmapviewdelegate,Ios,Mkmapview,Mapkit,Mkannotation,Mkmapviewdelegate,我正试图在地图视图中标记一个位置 首先,我在这样一个单独的类中实现了MKAnnotation协议 AddressAnnotation.h #import <Foundation/Foundation.h> #import <MapKit/MapKit.h> @interface AddressAnnotation : NSObject <MKAnnotation> @property (nonatomic, readonly) CLLocationCoor
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
然后在视图控制器中,我实现了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;
}
不过,我一直遇到以下错误
-[AddressAnnotation setCoordinate:]:发送到实例的选择器无法识别
我不确定我做错了什么。有人能帮我吗
谢谢。您的问题是
坐标属性是只读的。此外,它已经由MKAnnotation
协议定义
当您实现协议定义@properties时,您实际上必须@syntentize这些属性,以便在类中创建支持实例变量(ivar),或者,您必须为这些属性实现自定义setter和getter
请记住:属性只不过是setter和getter方法,可以选择由ivar支持。由ivar支持是@属性的默认行为
因此,简而言之,要解决AddressAnnotion.h
文件中的问题,请删除coordinate
属性,并在AddressAnnotion.m
文件中添加:
// after the line @implementation Address Annotation
@syntetize coordinate = _coordinate;
问题是您定义了一个只读坐标特性。因此,在尝试设置时会出现异常。只需删除坐标属性定义,因为这已由MKAnnotation协议提供。我不知道您为什么被否决,但您是对的。这就是问题所在。谢谢,我设法改正了。:)我不得不接受rist的回答,因为他首先在这里发布了它,但感谢详细的回答。如果属性是在协议中定义的,就不再需要合成属性了。事实上,如果你不这样做,你会从Xcode得到一个警告。我让它工作了。谢谢但是屏幕上显示的区域不是标记区域。当应用程序启动时,我如何关注pin所在的区域;mapRegion.center=坐标;mapRegion.span.latitudeDelta=0.05;mapRegion.span.longitudeDelta=0.05;[地图视图设置区域:区域动画:是]
- (void)viewDidLoad
{
[super viewDidLoad];
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(34.421496, -119.70182);
AddressAnnotation *pinAnnotation = [[AddressAnnotation alloc] initWithCoordinates:coordinate];
[self.mapView addAnnotation:pinAnnotation];
}
// after the line @implementation Address Annotation
@syntetize coordinate = _coordinate;