2017-09-15 86 views
0

我为Xamarin表单地图实现了一个自定义的渲染器来实现一个Tap事件。Xamarin表单地图点击手势IOS

我的PCL我有这样的代码:

public class ExtMap : Map 
    { 
     /// <summary> 
     /// Event thrown when the user taps on the map 
     /// </summary> 
     public event EventHandler<MapTapEventArgs> Tapped; 

     #region Constructors 

     /// <summary> 
     /// Default constructor 
     /// </summary> 
     public ExtMap() 
     { 

     } 

     /// <summary> 
     /// Constructor that takes a region 
     /// </summary> 
     /// <param name="region"></param> 
     public ExtMap(MapSpan region) 
      : base(region) 
     { 

     } 

     #endregion 

     public void OnTap(Position coordinate) 
     { 
      OnTap(new MapTapEventArgs { Position = coordinate }); 
     } 

     protected virtual void OnTap(MapTapEventArgs e) 
     { 
      var handler = Tapped; 

      if (handler != null) 
       handler(this, e); 
     } 
    } 

而在我的IOS项目验证码:

public class ExtMapRenderer : MapRenderer 
    { 
     private readonly UITapGestureRecognizer _tapRecogniser; 

     public ExtMapRenderer() 
     { 
      _tapRecogniser = new UITapGestureRecognizer(OnTap) 
      { 
       NumberOfTapsRequired = 1, 
       NumberOfTouchesRequired = 1 
      }; 
     } 

     private void OnTap(UITapGestureRecognizer recognizer) 
     { 
      var cgPoint = recognizer.LocationInView(Control); 

      var location = ((MKMapView)Control).ConvertPoint(cgPoint, Control); 

      ((ExtMap)Element).OnTap(new Position(location.Latitude, location.Longitude)); 
     } 

     protected override void OnElementChanged(ElementChangedEventArgs<View> e) 
     { 
      if (Control != null) 
       Control.RemoveGestureRecognizer(_tapRecogniser); 

      base.OnElementChanged(e); 

      if (Control != null) 
      { 
       var nativeMap = Control as MKMapView; 
       nativeMap.ShowsUserLocation = true; 
       Control.AddGestureRecognizer(_tapRecogniser); 
      } 

     } 
    } 

在模拟器有时会引发该事件,但我必须点击任意一个很多时间在地图上。 在我的iPhone中,事件从未被提出。

在Android手机&模拟器,事件工作正常,所以我怀疑IOS项目中有一个不好的实现,但我不知道如何改进它。

回答

1

我有一个iOS地图渲染器,点击工作正常。

我OnElementChanged是你有点不同:

private MKMapView Map => Control as MKMapView; 

protected override void OnElementChanged(ElementChangedEventArgs<View> e) 
{ 
    base.OnElementChanged(e); 

    if (e.OldElement != null && Map != null) 
    { 
     Control?.RemoveGestureRecognizer(_tapRecogniser); 
    } 

    if (e.NewElement != null) 
    { 
     Control?.AddGestureRecognizer(_tapRecogniser); 
    } 
} 
+0

它的好,但有时它没有工作....我在以前实现我没有工作,在的MKMapView一切,那可能是我错过了什么? – OrcusZ