【发布时间】:2015-10-07 11:33:55
【问题描述】:
我正在创建一个 MapView,我想在其中显示一些自定义注释。
所以我认为通常你所做的就是使用AddAnnotation 方法将一些IMKAnnotation 添加到MKMapView。我确保在主线程上调用它,例如:
new NSObject().InvokeOnMainThread(() => {
_mapView.AddAnnotation(myNewAnnotation);
});
添加这些之后,我确实看到MKMapView 现在包含我在使用调试器检查时在Annotations 属性中添加的所有注释。
但是,问题是 GetViewForAnnotation 永远不会被调用,无论我怎么做。
我试过了:
_mapView.GetViewForAnnotation += ViewForAnnotation;
private MKAnnotationView ViewForAnnotation(MKMapView mapView, IMKAnnotation annotation) {
// do stuff here
}
我已经尝试实现我自己的委托:
public class MyMapViewDelegate : MKMapViewDelegate
{
public override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation) {
// do stuff
}
}
_delegate = new MyMapViewDelegate();
_mapView.Delegate = _delegate;
我尝试过使用WeakDelegate:
public class MapView : ViewController, IMKMapViewDelegate
{
private MKMapView _mapView;
public override void ViewDidLoad() {
_mapView = new MKMapView();
_mapView.WeakDelegate = this;
}
[Export("mapView:viewForAnnotation:")]
public MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation) {
// do stuff
}
}
似乎没有任何东西触发GetViewForAnnotation 方法。任何想法我做错了什么?
编辑:
我现在拥有的更多细节。
[Register("MapView")]
public class MapView : MvxViewController<MapViewModel>
{
private MKMapView _mapView;
private NMTAnnotationManager _annotationManager;
public override void ViewDidLoad()
{
base.ViewDidLoad();
_mapView = new MKMapView();
_mapView.GetViewForAnnotation += GetViewForAnnotation;
_annotationManager = new NMTAnnotationManager(_mapView);
var bindSet = this.CreateBindingSet<MapView, MapViewModel>();
bindSet.Bind(_annotationManager).For(a => a.ItemsSource).To(vm => vm.Locations).OneWay();
bindSet.Apply();
Add(_mapView);
View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
View.AddConstraints(
_mapView.AtTopOf(View),
_mapView.AtLeftOf(View),
_mapView.AtRightOf(View),
_mapView.AtBottomOf(View));
}
private MKAnnotationView GetViewForAnnotation(MKMapView mapview, IMKAnnotation annotation)
{
return null;
}
}
NMTAnnotationManager 只是弱订阅了INotifyCollectionChanged 事件,ObservableCollection 在绑定中用作ItemsSource。当集合发生变化时,它只是从MKMapView 中添加和删除注释,这里没有什么神奇的事情发生。我已经验证它确实在这种情况下添加了 13 个不同的 IMKAnnotation 实例到 MKMapView 并且可以在它的 Annotations 属性中检查它们。
正如@Philip 在他的回答中所建议的那样,GetViewForAnnotation 确实在将注释添加到 MapView 之前设置好了。但是如果我在方法中放置断点或一些跟踪,它就永远不会被命中。
上面的代码相同,只是简单的MKMapViewDelegate如下:
public class MyMapViewDelegate : MKMapViewDelegate
{
public override void MapLoaded(MKMapView mapView)
{
Mvx.Trace("MapLoaded");
}
public override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
Mvx.Trace("GetViewForAnnotation");
return null;
}
}
也不行。虽然每次渲染地图都会触发MapLoaded事件,但是为什么GetViewForAnnotation没有触发呢?
【问题讨论】:
标签: xamarin xamarin.ios mkannotationview mkmapviewdelegate