在iOS

时间:2017-11-07 09:06:04

标签: c# xamarin xamarin.ios xamarin.forms custom-renderer

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

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

2 个答案:

答案 0 :(得分:4)

最佳解决方案:

Appearance

中的方法ViewWillAppear中设置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);
        }
    }
}

enter image description here

答案 1 :(得分:2)

您可以使用appearance API更改标签页上的背景颜色

OR

你可以使用自定义渲染(正如你在这里尝试的那样)

[assembly: ExportRenderer(typeof(TabbedPage), typeof(TabbedPageCustom))]

namespace MobileCRM.iOS {     


public class TabbedPageCustom : TabbedRenderer  {    

public TabbedPageCustom ()   {      

   TabBar.TintColor = MonoTouch.UIKit.UIColor.Black;
   TabBar.BarTintColor = MonoTouch.UIKit.UIColor.Blue;  
   TabBar.BackgroundColor = MonoTouch.UIKit.UIColor.Green;         
}    

}

}

希望你能继续......