2017-09-15 84 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