Wednesday, August 19, 2015

Different images for selected and unselected using Xamarin Forms Tab Bar

This is just a simple hack for iOS using Xamarin Forms and icons for a TabbedPage.

Problem definition

In Xamarin Forms, the icon of the tab bar is fetched from what ever image you reference in the Icon property of the page added to the TabbedPage. This image is grayed out if unselected and filled in with the defined color when selected.
However, sometimes you want to display a different image if unselected or selected and there is no build in way to specify this nicely.

Solution

The solution is a small hack. Simply add event handlers to the Appearing and Disappearing events and reset the images to your liking.

         var activeImage = "active";
            var inactiveImage = "inactive";

            var tab1 = new AnotherPage();
            tab1.Title = "Check in";
            tab1.Icon = new FileImageSource() { File = activeImage };
            tab1.Appearing += (s, a) => tab1.Icon = new FileImageSource() { File = activeImage };
            tab1.Disappearing += (s, a) => tab1.Icon = new FileImageSource() { File = inactiveImage };



Summary

Should it be done? Probably not, but if your out of options (that is your customer insist of doing it in such way) then this is an option.

Also worth noting is that the images will flicker if the debugger is attached. There is no visible delay when running it in release.

No comments:

Post a Comment