重写Xamarin TabbedPage,自定义文字大小和字体
在Xamarin项目中如果你使用了TabbedPage,并且有需要更改文字的大小或字体,这个需要自定义实现,下面跟随我们来实现如下:
1、定义CustomerTabbedPage
1 public class CustomerTabbedPage : TabbedPage 2 { 3 4 }
2、iOS平台实现代码
[assembly: ExportRenderer(typeof(TabbedPage), typeof(CustomTabbedPageRenderer))] namespace Test.iOS.Renderers { public class CustomTabbedPageRenderer : TabbedRenderer { public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); UpdateAllTabBarItems(); } /// <summary> /// Updates the tab bar item for each page included in the TabbedPage. /// </summary> private void UpdateAllTabBarItems() { foreach (var controller in ViewControllers) { controller.TabBarItem.SetTitleTextAttributes(StandardAttributes, UIControlState.Normal); } } /// <summary> /// Stores the UITextAttributes for this class. /// </summary> /// <value>The standard attributes.</value> private static UITextAttributes StandardAttributes { get; } = new UITextAttributes() { Font = UIFont.FromName("ContrafaceText-Bold", 12) }; } }
3、Android平台实现
[assembly: ExportRenderer(typeof(Xamarin.Forms.TabbedPage), typeof(CustomTabbedPageRenderer))] namespace Test.Droid.Renderers { public class CustomTabbedPageRenderer : TabbedPageRenderer { BottomNavigationView bottomNavigationView; public CustomTabbedPageRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.TabbedPage> e) { base.OnElementChanged(e); if (e.NewElement == null || e.OldElement != null) return; if (e.NewElement != null) { bottomNavigationView = (GetChildAt(0) as RelativeLayout).GetChildAt(1) as BottomNavigationView; //Call to change the font ChangeFont(); } } //Change Tab font void ChangeFont() { Typeface fontFace = Typeface.CreateFromAsset(this.Context.Assets, "ContrafaceText-Bold.ttf"); if (!(bottomNavigationView.GetChildAt(0) is BottomNavigationMenuView bottomNavMenuView)) return; for (int i = 0; i < bottomNavMenuView.ChildCount; i++) { var item = bottomNavMenuView.GetChildAt(i) as BottomNavigationItemView; var itemTitle = item.GetChildAt(1); var smallTextView = ((TextView)((BaselineLayout)itemTitle).GetChildAt(0)); var largeTextView = ((TextView)((BaselineLayout)itemTitle).GetChildAt(1)); smallTextView.SetTypeface(fontFace, TypefaceStyle.Normal); largeTextView.SetTypeface(fontFace, TypefaceStyle.Normal); } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本