Search code examples
c#webviewmauitabbarapp-shell

Swiping elements horizontally inside .NET MAUI Shell tabs


I have 2 tabs in the AppShell.xaml file implemented with the following code:

<TabBar>
    <Tab Route="Tabs">
        <ShellContent
            Title="FirstPage"
            ContentTemplate="{DataTemplate local:FirstPage}"
            Route="FirstPage" />
        <ShellContent
            Title="SecondPage"
            ContentTemplate="{DataTemplate local:SecondPage}"
            Route="SecondPage" />
    </Tab>
</TabBar>

FirstPage has a WebView in which swiping left and right should be used at certain parts of its content for scrolling some text horizontally.

The problem is that swiping to the right also switches to the next tab and that action takes priority over scrolling the text.

Is there a way to override the gesture and scroll the text within the WebView when the scrollable text is swiped and of course change to the next tab when other parts of the WebView without horizontally scrollable text are swiped?


Solution

  • I reproduced your problem, which needs to be solved by using ShellRenderer.

    First, create a class that inherits from Shellrenderer, I named it CustomShellRenderer:

    #if ANDROID
        public class CustomShellRenderer : ShellRenderer
        {
            protected override IShellSectionRenderer CreateShellSectionRenderer(ShellSection shellSection)
            {
                return new CustomShellSectionRenderer(this);
            }
        }
    
        public class CustomShellSectionRenderer : ShellSectionRenderer
        {
            public CustomShellSectionRenderer(IShellContext shellContext) : base(shellContext)
            {
            }
    
            public override Android.Views.View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
            {
                var result =  base.OnCreateView(inflater, container, savedInstanceState);
                SetViewPager2UserInputEnabled(false);
                return result;
            }
            protected override void SetViewPager2UserInputEnabled(bool value)
            {
                base.SetViewPager2UserInputEnabled(false);
            }
        }
    #endif
    }
    

    Then register the handler in MauiProgram.cs:

    builder
                    .UseMauiApp<App>()
                    .ConfigureFonts(fonts =>
                    {
                        fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                        fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                    })
                    .ConfigureMauiHandlers
                    (
                        handlers =>
                        {
    #if ANDROID
                            handlers.AddHandler(typeof(Shell), typeof(CustomShellRenderer));
    #endif
                        }