Skip to main content
 首页 » 编程设计

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

2024年01月22日42kevingrace

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

请您参考如下方法:

最佳解决方案:

TabbedRenderer 的方法 ViewWillAppear 中设置 Appearance

代码:

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