Search code examples
xamarin.iosuitabbarcontroller

How do I change the background color of a tabbed page in Xamarin iOS?


I need to change the background color of the currently tabbed page in my UITabBarController. I've searched through every stackoverflow post I could find but nothing worked for me. I thought there would be something like UITabBar.Appearance.SelectedImageTintColor, just for the background color but it doesn't seem so.

For example, I want to change the color of that part when I am on the right tab:

I want to change the color of that part when I am on the right tab

Does someone know how to do that?


Solution

  • The trick is to use the SelectionIndicatorImage Property of the UITabBar and generate a completely filled image with your desired color using the following method:

    private 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.Green); //change color if necessary
            context.FillRect(rect);
        }
        UIImage image = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();
        return image;
    }
    

    To initialize everything we override ViewWillLayoutSubviews() like this:

    public override void ViewWillLayoutSubviews() 
    {
        base.ViewWillLayoutSubviews();
        
        // The tabbar height will always be 49 unless we force it to reevaluate it's size on runtime ...
        myTabBar.InvalidateIntrinsicContentSize();
    
        double height = myTabBar.Frame.Height;
        CGSize size = new CGSize(new nfloat(myTabBar.Frame.Width / myTabBar.Items.Length, height));
    
        // Now get our all-green image...
        UIImage image = ImageWithColor(size);
        
        // And set it as the selection indicator
        myTabBar.SelectionIndicatorImage = image;
    }
    

    As mentioned in this article (google translating it step by step when necessary lol) calling InvalidateIntrinsicContentSize() will force the UITabBar to reevaluate it's size and will get you the actual runtime height of the tab bar (instead of the constant 49 height value from XCode).