首页 > 解决方案 > FontAwesome 标签渲染器 iOS 麻烦

问题描述

我试图弄清楚如何使这个 Android 示例与 iOS 一起工作:

using System;
using md.UserControls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

namespace md.iOS.CustomRenderers
{
    public class FontAwesomeLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement == null)
            {
                Control.Typeface = Typeface.CreateFromAsset(Forms.Context.Assets,
                    "Fonts/" + FontAwesomeLabel.FontAwesomeName + ".ttf");
            }
        }
    }
}

有问题的部分是这样的:

Control.Typeface = Typeface.CreateFromAsset(Forms.Context.Assets,
                    "Fonts/" + FontAwesomeLabel.FontAwesomeName + ".ttf");

Control.Typeface 或只是 Typeface 给出了一些问题(红色下划线)。

iOS中的字体是什么?

希望有人可以帮助并提前感谢:-)

标签: xamarin.formsxamarin.iosfont-awesome

解决方案


只需Style为您想要具有此字体类型的标签定义一个。您可以在 XAML 中执行此操作,方法是FontFamily这样定义:

<Style x:Key="NameOfYourLabelStyle" TargetType="Label">
    <Setter Property="FontFamily">
        <OnPlatform x:TypeArguments="x:String">
            <On Platform="Android">Fonts/FontAwesome.otf#FontAwesome</On>
            <On Platform="UWP">/Assets/Fonts/FontAwesome.otf#FontAwesome</On>
            <On Platform="iOS">FontAwesome</On>
        </OnPlatform>
    </Setter>
</Style>    

确保将 *.otf(或 *.ttf)字体文件添加到Resources文件夹中,并确保在info.plist文件中添加特定键,如下所示:

<key>UIAppFonts</key>
<array>
    <string>Fonts/FontAwesome.otf</string>
</array>

注意:在我的例子中,字体文件位于 Resources/Fonts/ 目录中

在此处输入图像描述

编辑:设置时实际发生的FontFamily事情与您在渲染器中所做的事情完全相同。签出Xamarin.Forms github 源UpdateFont中的方法和 LabelRenderer在其中调用的方法。ToTypeFace


推荐阅读