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

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

我需要在我的 UITabBarController 中更改当前标签页的背景颜色。我搜索了我能找到的每个 Whosebug post,但对我没有任何帮助。我以为会有 UITabBar.Appearance.SelectedImageTintColor 之类的东西,只是为了背景颜色,但似乎不是。

比如我想在右边的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, 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, 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;
}

要初始化我们覆盖 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 中所述(google 必要时逐步翻译它 lol)调用 InvalidateIntrinsicContentSize() 将强制 UITabBar 重新评估它的大小并为您提供实际的运行时高度标签栏的高度(而不是 XCode 中的常量 49 高度值)。