Search code examples
swipemaui

Trying to implement MAUI Swipe to change Image


I'm creating a simple page to change the image by swiping. Swipe left gives the next image and swipe right the previous. Unfortunately the swipe events don't trigger.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Alm.MainPage">
    
    <SwipeView SwipeEnded="SwipeView_SwipeEnded" Threshold="200">
        <SwipeItemView>             
        <Image >
            <Image.Source>
                <UriImageSource x:Name="Sorsa" Uri="https://someurl.com/someimage.jpg"></UriImageSource>
            </Image.Source>
        </Image>
        </SwipeItemView>
    </SwipeView>
 
</ContentPage>

And the event is:

private void SwipeView_SwipeChanging(object sender, SwipeChangingEventArgs e) {
    if (e.SwipeDirection == SwipeDirection.Left)
        Sorsa.Uri = HaeEdellinen();
    if (e.SwipeDirection == SwipeDirection.Right)
        Sorsa.Uri = HaeSeuraava();
}

but it never fires.


Solution

  • You can directly add the Swipe GestureRecognizer to the image and detect the swipe direction: Left or Right to change the source for the image. Here's the code snippet below for your reference:

    Xaml:

    
    <Image x:Name="img" HeightRequest="150" WidthRequest="150" Source="logo.png" > 
             <Image.GestureRecognizers>
                     <SwipeGestureRecognizer Direction="Left" 
                                             Swiped="SwipeGestureRecognizer_Left"/>
    
    
                     <SwipeGestureRecognizer Direction="Right" 
                                             Swiped="SwipeGestureRecognizer_Right"/>
    
             </Image.GestureRecognizers>
    </Image>
    
    

    Code-behind:

    private void SwipeGestureRecognizer_Left(object sender, SwipedEventArgs e) 
    {
        img.Source = "logo.png";
    }
    
    private void SwipeGestureRecognizer_Right(object sender, SwipedEventArgs e)
    {
        img.Source = "uk.jpg";
    }