How can we detect swipe gestures in .NET Maui Blazor Hybrid? I have seen the swipe gesture example in native .NET Maui but I couldn't find any example of the .NET Maui Blazor Hybrid. Please help me
CodePudding user response:
.NET Maui Blazor Hybrid
doesn't have built-in support for swipe gestures. You can create your own solution by handling the various @ontouch***
EventCallback
's. Here is a very basic SwipeArea
component implementation:
SwipeArea.razor:
<div @attributes="UserAttributes" style="@Style"
@ontouchstart="OnTouchStart" @ontouchstart:stopPropagation
@ontouchend="OnTouchEnd" @ontouchend:stopPropagation
@ontouchcancel="OnTouchCancel" @ontouchcancel:stopPropagation>
@ChildContent
</div>
@code {
private double? _xDown;
private double? _yDown;
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public Action<SwipeDirection> OnSwipe { get; set; }
[Parameter]
public string Class { get; set; }
[Parameter]
public string Style { get; set; }
[Parameter]
public Dictionary<string, object> UserAttributes { get; set; } = new Dictionary<string, object>();
private void OnTouchStart(TouchEventArgs args)
{
_xDown = args.Touches[0].ClientX;
_yDown = args.Touches[0].ClientY;
}
private void OnTouchEnd(TouchEventArgs args)
{
if (_xDown == null || _yDown == null)
{
return;
}
var xDiff = _xDown.Value - args.ChangedTouches[0].ClientX;
var yDiff = _yDown.Value - args.ChangedTouches[0].ClientY;
if (Math.Abs(xDiff) < 100 && Math.Abs(yDiff) < 100)
{
_xDown = null;
_yDown = null;
return;
}
if (Math.Abs(xDiff) > Math.Abs(yDiff))
{
if (xDiff > 0)
{
InvokeAsync(() => OnSwipe(SwipeDirection.RightToLeft));
}
else
{
InvokeAsync(() => OnSwipe(SwipeDirection.LeftToRight));
}
}
else
{
if (yDiff > 0)
{
InvokeAsync(() => OnSwipe(SwipeDirection.BottomToTop));
}
else
{
InvokeAsync(() => OnSwipe(SwipeDirection.TopToBottom));
}
}
_xDown = null;
_yDown = null;
}
private void OnTouchCancel(TouchEventArgs args)
{
_xDown = null;
_yDown = null;
}
}
SwipeDirection.cs:
public enum SwipeDirection
{
None,
LeftToRight,
RightToLeft,
TopToBottom,
BottomToTop
}
Usage example:
<SwipeArea OnSwipe="OnSwipe" Class="h-100 pt-1">
@* wrap the area that you want to detect swipe gestures in SwipeArea component *@
</SwipeArea>
@code {
private SwipeDirection _swipeDirection = SwipeDirection.None;
private void OnSwipe(SwipeDirection swipeDirection)
{
_swipeDirection = swipeDirection;
// do stuff based on swipe direction
}
}