简体   繁体   中英

Xamarin.Forms: How to change FontFamily of tabs in TabbedPage?

How do I change the font style and size on tabs?

在此处输入图像描述 MainPage.xaml

<TabbedPage.Children>
    <local:Page1/>
    <local:Page2/>
    <local:Page3/>
</TabbedPage.Children>

Page1.xaml

<ContentPage 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"
             mc:Ignorable="d"
             x:Class="HelpMe.Page1"
             Title="Page 1">

Unfortunately, there is no direct cross platform way of achieving this in Xamarin.Forms

You have to write your own Effect or create a Custom renderer deriving from the native platform renderer. In your case it will be TabbedPageRenderer . Once you are able to register your custom renderer on the platform, you should be able to access the native Views on the platform and use platform specific APIs and set native properties as desired.

Update:

To help you achieve what I said above, here is the code for Android. You would do something similar on iOS

[assembly: ExportRenderer(typeof(TabbedPage), typeof(CustomTabbedPageRenderer))]

namespace YourNamespace.Renderers
{
    public class CustomTabbedPageRenderer : TabbedPageRenderer
    {
        public CustomTabbedPageRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
        {
            base.OnElementChanged(e);

            if (Element == null)
            {
                return;
            }

            UpdateTabLayout();

        }


        private void UpdateTabLayout()
        {
            if (!(GetChildAt(1) is TabLayout tabLayout)) return;

            var vg = (ViewGroup) tabLayout.GetChildAt(0);
            var tabsCount = vg.ChildCount;
            for (var i = 0; i < tabsCount; i++)
            {
                var vgTab = (ViewGroup) vg.GetChildAt(i);
                var tabChildCount = vgTab.ChildCount;
                for (var j = 0; j < tabChildCount; j++)
                {
                    var tabViewChild = vgTab.GetChildAt(j);
                    if (tabViewChild is TextView textView)
                    {
                        textView.SetTypeface(Typeface.SansSerif, TypefaceStyle.Italic);
                    }
                }
            }

        }
    }
}

The above code is trying to set the font as SansSerif with the Italic style and I have tested the code, it works as expected.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM