Search code examples
c#xamarinxamarin.iosxamarin.formscustom-renderer

Background color of selected TabBarItem in Xamarin on iOS


Using Xamarin.Forms, I have a custom TabbedPageRenderer in iOS. Now, I can change the text color on a selected TabBarItem, but I can't change the background color of the selected tab. Does anyone know how?

class CustomTabbedPageRenderer : TabbedRenderer
{
   public override UIViewController SelectedViewController
   {
       get
       {
           UITextAttributes attr = new UITextAttributes();
           attr.TextColor = UIColor.White;
           if (base.SelectedViewController != null)
           {
               base.SelectedViewController.TabBarItem.SetTitleTextAttributes(attr, UIControlState.Normal);                  
               // TODO: How to set background color for ONE item?
           }
           return base.SelectedViewController;
       }
       set
       {
           base.SelectedViewController = value;
       }
    }
}

Solution

  • The Best Solution:

    Set Appearance in method ViewWillAppear in TabbedRenderer

    Code:

    [assembly: ExportRenderer(typeof(TabbedPage), typeof(CustomTabbedPageRenderer))]
    namespace TabbedPageWithNavigationPage.iOS
    {
        class CustomTabbedPageRenderer : TabbedRenderer
        {
            public UIImage imageWithColor(CGSize size)
            {
                CGRect rect = new CGRect(0, 0, size.Width, size.Height);
                UIGraphics.BeginImageContext(size);
    
                using (CGContext context = UIGraphics.GetCurrentContext())
                {
                    context.SetFillColor(UIColor.Red.CGColor);
                    context.FillRect(rect);
                }
    
                UIImage image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();
    
                return image;
            }
    
            public override void ViewWillAppear(bool animated)
            {
                base.ViewWillAppear(animated);
    
                CGSize size = new CGSize(TabBar.Frame.Width / TabBar.Items.Length, TabBar.Frame.Height);
    
                //Background Color
                UITabBar.Appearance.SelectionIndicatorImage = imageWithColor(size);
                //Normal title Color
                UITabBarItem.Appearance.SetTitleTextAttributes(new UITextAttributes { TextColor = UIColor.White }, UIControlState.Normal);
                //Selected title Color
                UITabBarItem.Appearance.SetTitleTextAttributes(new UITextAttributes { TextColor = UIColor.Black }, UIControlState.Selected);
            }
        }
    }
    

    enter image description here