iOS上Xamarin中所选TabBarItem的背景颜色

Mys*_*gan 1 c# custom-renderer xamarin.ios xamarin xamarin.forms

使用Xamarin.Forms,我在iOS中有一个自定义的TabbedPageRenderer。现在,我可以更改所选TabBarItem上的文本颜色,但是不能更改所选Tab的背景颜色。有人知道吗?

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;
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

Col*_*SFT 5

最佳解决方案:

AppearanceViewWillAppear中设置方法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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明