You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让.NET MAUI中TabBar的Tab标题文本居中显示?

实现.NET MAUI TabBar标题居中显示

你可以基于已使用的Shell自定义渲染器,针对Android和iOS平台分别调整Tab标题的对齐方式:

Android平台修改

在Android的自定义Shell渲染器中,添加标题居中的逻辑:

using Android.Content;
using Microsoft.Maui.Controls.Platform;

[assembly: ExportRenderer(typeof(AppShell), typeof(你的项目命名空间.Android.CustomShellRenderer))]
namespace 你的项目命名空间.Android
{
    public class CustomShellRenderer : ShellRenderer
    {
        public CustomShellRenderer(Context context) : base(context)
        {
        }

        protected override IShellBottomNavViewAppearanceTracker CreateBottomNavViewAppearanceTracker(ShellItem shellItem)
        {
            return new CustomBottomNavAppearanceTracker();
        }
    }

    public class CustomBottomNavAppearanceTracker : ShellBottomNavViewAppearanceTracker
    {
        public override void SetAppearance(AndroidX.Navigation.UI.BottomNavigationView bottomView, IShellAppearanceElement appearance)
        {
            base.SetAppearance(bottomView, appearance);
            
            // 遍历所有Tab项,设置标题居中
            for (int i = 0; i < bottomView.Menu.Size(); i++)
            {
                var menuItem = bottomView.Menu.GetItem(i);
                var titleView = menuItem.ActionView as Android.Widget.TextView;
                if (titleView != null)
                {
                    titleView.Gravity = Android.Views.GravityFlags.Center;
                }
            }
        }
    }
}

iOS平台修改

在iOS的自定义Shell渲染器中,调整UITabBarItem的文本对齐属性:

using UIKit;
using Microsoft.Maui.Controls.Platform;

[assembly: ExportRenderer(typeof(AppShell), typeof(你的项目命名空间.iOS.CustomShellRenderer))]
namespace 你的项目命名空间.iOS
{
    public class CustomShellRenderer : ShellRenderer
    {
        protected override IShellTabBarAppearanceTracker CreateTabBarAppearanceTracker()
        {
            return new CustomTabBarAppearanceTracker();
        }
    }

    public class CustomTabBarAppearanceTracker : ShellTabBarAppearanceTracker
    {
        public override void UpdateLayout(UITabBarController controller)
        {
            base.UpdateLayout(controller);
            
            foreach (UITabBarItem item in controller.TabBar.Items)
            {
                // 设置标题居中对齐
                item.SetTitleTextAttributes(new UITextAttributes
                {
                    TextAlignment = UITextAlignment.Center
                }, UIControlState.Normal);
                item.SetTitleTextAttributes(new UITextAttributes
                {
                    TextAlignment = UITextAlignment.Center
                }, UIControlState.Selected);
            }
        }
    }
}

注意事项

  • 请将代码中的你的项目命名空间替换为你实际的项目命名空间
  • 如果已有自定义渲染器类,直接在对应方法中添加标题对齐的代码即可,无需重复创建类

内容的提问来源于stack exchange,提问作者David Shochet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 08:45:49