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

如何阻止Xamarin.Forms中TabbedPage选中时图标上移

解决Xamarin.Forms TabbedPage选中图标上浮的问题

你遇到的这个选中Tab时图标轻微上移的弹出效果,是iOS平台原生UITabBar的默认行为,Xamarin.Forms本身没有直接提供XAML属性来关闭它,但我们可以通过自定义渲染器轻松禁用这个动画,具体步骤如下:

1. 创建自定义TabbedPage子类

在你的共享项目中新建一个继承自TabbedPage的类,用来标记我们需要自定义渲染的页面:

using Xamarin.Forms;

namespace StudioDen
{
    public class CustomTabbedPage : TabbedPage
    {
        // 不需要额外代码,仅作为标记类使用
    }
}

2. 修改MainPage.xaml的根节点

把原来的TabbedPage替换成我们刚创建的CustomTabbedPage,记得添加对应的命名空间:

<?xml version="1.0" encoding="utf-8" ?>
<local:CustomTabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:views="clr-namespace:StudioDen.View"
             xmlns:local="clr-namespace:StudioDen"
             mc:Ignorable="d"
             x:Class="StudioDen.MainPage"
             BarBackgroundColor="#FFDA00"
             UnselectedTabColor="Black"
             SelectedTabColor="Black">

<!-- 你的5个NavigationPage子内容保持不变,此处省略 -->

</local:CustomTabbedPage>

3. 在iOS项目中添加自定义渲染器

iOS平台需要我们重写TabbedPage的渲染逻辑,禁用原生的上浮动画:

using Foundation;
using StudioDen;
using StudioDen.iOS;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(CustomTabbedPage), typeof(CustomTabbedPageRenderer))]
namespace StudioDen.iOS
{
    public class CustomTabbedPageRenderer : TabbedRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (TabBar != null)
            {
                // 设置Tab项填充整个TabBar,直接取消选中时的上浮效果
                TabBar.ItemPositioning = UITabBarItemPositioning.Fill;
                
                // 可选:如果还想统一选中/未选中的文字大小(避免文字变大)
                TabBar.ItemAppearance.Selected.TitleTextAttributes = new UITextAttributes
                {
                    Font = UIFont.SystemFontOfSize(10) // 替换成你需要的字体大小
                };
                TabBar.ItemAppearance.Normal.TitleTextAttributes = new UITextAttributes
                {
                    Font = UIFont.SystemFontOfSize(10)
                };
            }
        }
    }
}

原理说明

iOS原生的UITabBar默认使用UITabBarItemPositioning.Centered布局,这种布局下选中的Tab图标会上浮以突出显示;我们将其改为Fill模式后,所有Tab项会均匀填充整个TabBar宽度,原生的上浮动画就会被自动禁用。

Android平台默认没有这个选中上浮的效果,所以不需要额外处理。

内容的提问来源于stack exchange,提问作者Dragos Stoian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:53:23