user6742877
user6742877

Reputation:

How to detect Xamarin Forms tabbed page click - iOS?

My scenario is, I have a Tabbed page in Xamarin Forms:

public partial class MainPage : TabbedPage
{
    public MainPage()
    {
        InitializeComponent();

        var playPage = new NavigationPage(new PlayPage())
        {
            Title = "Play",
            Icon = "play.png"
        };
        var settingsPage = new NavigationPage(new SettingsPage())
        { 
            Title = "Settings",
            Icon = "settings.png"
        };
        var favoritesPage = new NavigationPage(new FavoritesPage())
        {
            Title = "Favorites",
            Icon = "fave.png"
        };
        var aboutPage = new NavigationPage(new AboutPage())
        {
            Title = "About",
            Icon = "info.png"
        };

        Children.Add(playPage);
        Children.Add(favoritesPage);
        Children.Add(settingsPage);
        Children.Add(aboutPage);
    }
}

I want to add a pause and play function to my app. On start up, the PlayPage would initially have the play.png icon and when I click on the PlayPage again it would change the icon to pause.png. Page is not changing just the page icon. Anyone has any idea how this could be done?

Edit:

So I have created a custom renderer, in OnElementChanged I utilize the ViewControllerSelected:

var tabbarController = (UITabBarController)this.ViewController;
if (null != tabbarController)
{
    tabbarController.ViewControllerSelected += OnTabBarReselected;
}

And my OnTabBarReselected I have:

private void OnTabBarReselected(object sender, UITabBarSelectionEventArgs e)
{
    switch (TabBar.SelectedItem.Title)
    {
       case "Play":
          TabBar.SelectedItem.Title = "Pause";
          TabBar.SelectedItem.Image = UIImage.FromFile("pause.png");
          break;
    }
}

This only does half of the work. It changes the Title of the selected tab bar from Play to Pause after I click on the same tab but not the Icon. The icon remains "play.png" until I get out of that tab page (selecting another tab). Anyone has any idea why?

Upvotes: 2

Views: 1804

Answers (1)

Steven Thewissen
Steven Thewissen

Reputation: 2981

You will need to implement a custom renderer to pull this off. There are some implementations on James Montemagno's blog where he talks about changing the icons.

This is however not necessarily related to your requirement of tapping the icon and changing that specific icon since all this code only runs when the page initially loads. It could be a nice starting point though. Check in there if there's a property on TabbedPage that changes when you tap on the current tab and change the icon at that point.

You also have a OnCurrentPageChanged event you can override in TabbedPage, but that isn't called when the page is already active.

Upvotes: 1

Related Questions