我正在创建一个 MapView,我想在其中显示一些自定义注释。
所以我认为通常你所做的就是IMKAnnotation
在MKMapView
使用AddAnnotation
方法中添加一些。我确保在主线程上调用它,例如:
new NSObject().InvokeOnMainThread(() => {
_mapView.AddAnnotation(myNewAnnotation);
});
添加这些之后,我确实看到now 包含我在使用调试器检查时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
事件。当集合更改时,它只是从 中添加和删除注释,这里没有任何神奇的事情发生。我已经验证它确实添加了不同的实例,在这种情况下为13,并且可以在它的属性中检查它们。ObservableCollection
ItemsSource
MKMapView
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
触发呢?