我有一个 mkannotation 位于一个 mapview 上,它有一个 mkannotationview 以及一个 calloutview,当单击它时会转到一个子 uiviewcontroller。我正在从标注的 uiviewcontroller 更新一些属性,但是在我完成后,我想移动注释在地图上的位置并更改注释标题和副标题。如何从标注的 uiviewcontoller 轻松做到这一点?处理这个最优雅的方法是什么?如果有人有代码示例,那就太好了。
谢谢
我有一个 mkannotation 位于一个 mapview 上,它有一个 mkannotationview 以及一个 calloutview,当单击它时会转到一个子 uiviewcontroller。我正在从标注的 uiviewcontroller 更新一些属性,但是在我完成后,我想移动注释在地图上的位置并更改注释标题和副标题。如何从标注的 uiviewcontoller 轻松做到这一点?处理这个最优雅的方法是什么?如果有人有代码示例,那就太好了。
谢谢
I'd create a protocol, say MapCallBackDelegate, to handle what you want to do. This avoids tightly coupled code. Put this in your map annotation view header file
@protocol MapCallBackDelegate
-(void)updateAnnotation:(id)whatEverParamsYouWant;
@end
Then make your Map View implement this protocol. When you create your map annotation view, give it a property
@property (nonatomic, retain) id<MapCallBackDelegate> callbackDelegate;
And when you add it to your map, set that property to self
myMapAnnotationView.callbackDelegate = self;
so when you want to change the title/subtitle/position, you just invoke that message on the callbkacDelegate.
This is elegant because it reduces tightly-coupled code, allows other objects to implement the same protocol for code reuse later, and promotes information hiding in your MapAnnotationView.
从地图中完全移除注记,对其进行更新,然后再次将其添加到地图中。这将确保地图注意到注释位置已更改。
尽管您可以按照@Caleb 的建议删除和添加注释,但另一种选择是coordinate
直接在要移动的注释上更新属性。
请注意,这仅在您的注释类实现时才有效,setCoordinate
这可以通过声明coordinate
as assign
(就像内置MKPointAnnotation
类一样)而不是readonly
. 地图视图将通过 KVO 看到更改并移动注释。
要让子视图控制器告诉地图视图控制器要更改哪个注释以及新坐标是什么,我建议使用委托+协议作为另一个答案建议。
最简单的方法是实际上不从子视图控制器中执行此操作。也许您的需求与我从问题中理解的不同,但乍一看我会做这样的事情:
在标题中:
@interface YourController
{
...
MKAnnotation *_latestDetailViewed;
}
...
@property(nonatomic, retain) MKAnnotation *latestDetailViewed;
@end
然后在 .m 中类似
@implementation YourController
...
@synthesize latestDetailViewed = _latestDetailViewed;
...
-(void) dealloc
{
...
self.latestDetailViewed = nil;
[super dealloc];
}
-(void) whereverYouLaunchYourDetailScreenFrom:(MKAnnotation*)detailAnnotation
{
self.latestDetailViewed = detailAnnotation;
// then create/push your view controller
}
-(void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if(_latestDetailViewed)
{
// Do whatever you want to the annotation here
self.latestDetailViewed = nil;
}
}
这样,当您返回地图时,您的更改就会生效。如果您真的一次只为一个注释启动一个详细视图,并且总是在两者之间返回地图,那么它应该可以工作,而无需您处理编写委托协议或触发 NSNotifications。
如果我误解了你的情况,请告诉我,我会给你一个不同的答案:)