FontAwesome Label渲染器iOS麻烦

时间:2018-09-05 10:20:51

标签: xamarin.forms xamarin.ios font-awesome

我正在尝试弄清楚如何使这个Android Example与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中的字体是什么?

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

2 个答案:

答案 0 :(得分:1)

只需为要具有此字体类型的标签定义一个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 /目录中

enter image description here

编辑:设置FontFamily时,幕后实际发生的操作与在渲染器中所做的完全相同。在Xamarin.Forms github sourcesUpdateFont中检出LabelRenderer方法,并在其中调用ToTypeFace方法。

答案 1 :(得分:0)

我建议您使用Iconize而不是编写自己的自定义渲染器。

这是一个简单的插件,可让您使用许多图标字体(例如Font Awesome)。

App.xaml.cs(插件的初始化):

Iconize.With(new FontAwesomeModule());

初始化后,您可以像这样使用它:

XAML页面:

xmlns:iconize="clr-namespace:Plugin.Iconize;assembly=Plugin.Iconize"

<iconize:IconLabel Text="fa-info" />

C#页面:

new IconLabel
{
    Text = "fa-info",
    FontSize = 55
};
相关问题