如何在Xamarin iOS中更改选项卡式页面的背景颜色? 更新

问题描述

我需要在UITabBarController中更改当前选项卡式页面的背景颜色。我搜索了所有可以找到的stackoverflow帖子,但没有任何帮助。我以为会有UITabBar.Appearance.SelectedImageTintColor之类的东西,只是用于背景颜色,但看起来并非如此。

例如,我想在右侧选项卡上更改该零件的颜色:

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

有人知道该怎么做吗?

解决方法

您可以在UITabBarController中调用以下代码

public xxxTabBarController()
{
   //...set ViewControllers

   this.TabBar.BarTintColor = UIColor.Red;
}

更新

//3.0 here is if you have three child page in tab,set it as the current value in your project
//
var size = new CGSize(TabBar.Frame.Width / 3.0,IsFullScreen());

this.TabBar.SelectionIndicatorImage = ImageWithColor(size,UIColor.Green);
 double IsFullScreen()
    {
        double height = 64;
        if (UIDevice.CurrentDevice.CheckSystemVersion(11,0))
        {
            if (UIApplication.SharedApplication.Delegate.GetWindow().SafeAreaInsets.Bottom > 0.0)
            {
                height = 84;
            }
        }
        return height;
    }

    UIImage ImageWithColor(CGSize size,UIColor color)
    {

        var rect = new CGRect(0,size.Width,size.Height);
        UIGraphics.BeginImageContextWithOptions(size,false,0);

        CGContext context =  UIGraphics.GetCurrentContext();
        context.SetFillColor(color.CGColor);

        context.FillRect(rect);

        UIImage image = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();
        return image;
        
    }
,

诀窍是使用UITabBar的SelectionIndicatorImage属性,并使用以下方法生成具有所需颜色的完全填充的图像:

private UIImage ImageWithColor(CGSize size)
{
    CGRect rect = new CGRect(0,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;
}

要初始化所有内容,我们可以像这样覆盖ViewWillLayoutSubviews()

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;
}

this article(谷歌在必要时逐步翻译)中所述,调用InvalidateIntrinsicContentSize()将强制UITabBar重新评估其大小,并为您提供标签栏的实际运行时高度(而不是XCode的常量49高度值的值)。