gpt4 book ai didi

ios - 带有自定义 MKAnnotation 的 MKMapView

转载 作者:可可西里 更新时间:2023-11-01 06:18:07 24 4
gpt4 key购买 nike

我有一个 MKMapView。我想在我的 map 上放置自定义 MKAnnotation。

它们是一些餐厅。我该怎么做?

我的问题是如何制作自定义 MKAnnotation?

谢谢,伙计们。

最佳答案

首先,让我们将自定义定义为不仅仅是标题和副标题。我们想要更改 MKAnnotation 的大小并包含一些自定义图形。

您可能希望自定义注释的两个部分:

  • MK注释
  • MKAnnotationView

对于最基本的 MKAnnotation,您只需采用协议(protocol)并为标题和副标题返回 nil,但您也可以在注释中携带更多信息,以便在点击附件指示器时进行扩展标注。您可以使用 addAnnotation 添加所有注释到 MKMapView:例如在 viewDidLoad 中。

MKAnnotation header

@interface CPAnnotation : NSObject <MKAnnotation> {
@private
CLLocationCoordinate2D _coordinate;
NSString *_title;
NSString *_subtitle;
}

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, readonly, copy) NSString *title;
@property (nonatomic, readonly, copy) NSString *subtitle;

- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate;
@end

MKAnnotation 实现

@implementation CPAnnotation
@synthesize coordinate = _coordinate;
@synthesize title = _title;
@synthesize subtitle = _subtitle;

- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate {
self = [super init];

if (self != nil) {
self.coordinate = coordinate;
}

return self;
}

- (NSString *)title {
return _title;
}

- (NSString *)subtitle {
return _subtitle;
}
@end

下一步是自定义掉落图钉的标注。为此,您需要自定义 MKAnnotationView。根据 Apple 的说法,默认情况下您不应该进行大量标注。他们推荐一个标准尺寸的标注,上面有一个按钮可以打开一个更大的标注。他们在蓝色圆圈图标中使用小写字母 i。这些图标可以通过 View 的 leftCalloutAccessoryView 和 rightCalloutAccessoryView 属性进行设置。如果您已经采用了 MKMapViewDelegate 协议(protocol)并将自己设置为 MKMapView 的委托(delegate),您将获得 viewForAnnotation: 的回调。

MKAnnotationView MKMapViewDelegate回调

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
static NSString *const kAnnotationReuseIdentifier = @"CPAnnotationView";

MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:kAnnotationReuseIdentifier];
if (annotationView == nil) {
annotationView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:kAnnotationReuseIdentifier] autorelease];
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeInfoLight];
}

return annotationView;
}

您可以在覆盖 drawRect 方法的自定义 View 中进一步自定义它,为图像属性提供图像,或者您甚至可以在 XIB 中实现 MKAnnotationView。值得进行一些实验。

Apple's WeatherAnnotationView Example说明重写 drawRect。

关于ios - 带有自定义 MKAnnotation 的 MKMapView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5007765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com