如何在MAUI TabbedPage无图标时将标签标题居中?
解决MAUI底部无图标标签页标题居中问题
问题描述
我想要创建两个无图标的底部标签页,但当前标签标题显示在标签区域的底部,期望无图标时标题能居中显示。使用的代码如下:
<TabbedPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Awakee.HomePage" xmlns:p="clr-namespace:Awakee.Views" xmlns:android="clr-namespace:Microsoft.Maui.Controls.PlatformConfiguration.AndroidSpecific;assembly=Microsoft.Maui.Controls" android:TabbedPage.ToolbarPlacement="Bottom" BarBackgroundColor="Grey"> <p:AddNewAwake Title="Add New" StyleClass=""/> <p:UpcomingAwake Title="Upcoming"/> </TabbedPage>
解决方案
Android平台
Android默认在无图标时会将标题靠下对齐,可通过以下两种方式调整:
- 平台特定属性快速调整
在TabbedPage中添加Android专属属性,强制Tab布局填充并居中内容:
<TabbedPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Awakee.HomePage" xmlns:p="clr-namespace:Awakee.Views" xmlns:android="clr-namespace:Microsoft.Maui.Controls.PlatformConfiguration.AndroidSpecific;assembly=Microsoft.Maui.Controls" android:TabbedPage.ToolbarPlacement="Bottom" BarBackgroundColor="Grey" android:TabbedPage.SetTabMode="Fixed" android:TabbedPage.SetTabGravity="Fill" BarItemColor="#888888" BarSelectedItemColor="#000000"> <p:AddNewAwake Title="Add New"/> <p:UpcomingAwake Title="Upcoming"/> </TabbedPage>
- 自定义渲染器(属性调整无效时使用)
创建Android平台的自定义渲染器,直接修改Tab项的布局:
using Android.Content; using Android.Support.Design.Widget; using Awakee; using Awakee.Droid; using Microsoft.Maui.Controls.Compatibility; using Microsoft.Maui.Controls.Compatibility.Platform.Android; [assembly: ExportRenderer(typeof(TabbedPage), typeof(CustomTabbedPageRenderer))] namespace Awakee.Droid { public class CustomTabbedPageRenderer : TabbedPageRenderer { public CustomTabbedPageRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e) { base.OnElementChanged(e); if (ViewGroup != null && ViewGroup.GetChildAt(1) is TabLayout tabLayout) { foreach (TabLayout.Tab tab in tabLayout.TabCount) { if (tab.CustomView == null) { var textView = new Android.Widget.TextView(Context) { Text = tab.Text, Gravity = Android.Views.GravityFlags.Center, TextSize = 14 }; tab.SetCustomView(textView); } } } } } }
iOS平台
iOS默认无图标时标题会自动居中,若未生效,可通过以下方式修复:
- 透明图标占位法
在ContentPage的后台代码中设置透明图标占位,强制标题居中:
public AddNewAwake() { InitializeComponent(); Title = "Add New"; // 使用1x1透明图片占位 TitleIcon = ImageSource.FromFile("transparent_icon.png"); }
- Info.plist样式调整
在Info.plist中添加TabBar标题位置调整参数:
<key>UITabBarItemTitlePositionAdjustment</key> <dict> <key>X</key> <integer>0</integer> <key>Y</key> <integer>-5</integer> </dict>
内容的提问来源于stack exchange,提问作者Subin
相关产品推荐
相关产品推荐

