iOS 上 Xamarin 中所选 TabBarItem 的背景颜色 [英] Background color of selected TabBarItem in Xamarin on iOS

查看:28
本文介绍了iOS 上 Xamarin 中所选 TabBarItem 的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Xamarin.Forms,我在 iOS 中有一个自定义的 TabbedPageRenderer.现在,我可以更改所选 TabBarItem 上的文本颜色,但我无法更改所选选项卡的背景颜色.有人知道怎么做吗?

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

推荐答案

最佳解决方案:

TabbedRenderer

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

这篇关于iOS 上 Xamarin 中所选 TabBarItem 的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆