【问题标题】:Apply custom font on label in xamarin.iOS在 xamarin.iOS 中的标签上应用自定义字体
【发布时间】:2018-05-18 20:51:31
【问题描述】:

我想在所有标签和条目中应用 Montserrat-Light 字体样式,我通过制作控件的渲染器来实现。 EntryRenderer 工作正常,但 LabelRenderer 给出 ArgumentNullException 消息:值不能为空。

  [assembly: ExportRenderer(typeof(Label), typeof(ExtendedLabelRenderer))]
namespace NewApp.iOS.Renderer
{
public class ExtendedLabelRenderer : LabelRenderer
{

    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);
        if (e.NewElement != null)
        {

            Control.Font = UIFont.FromName("Montserrat-Light", 10f);

        }
    }
}
}

【问题讨论】:

  • 不,不是,因为我应用了背景颜色并且效果很好
  • 那么什么是null呢?你调试了吗?
  • 是的,但它总是在 Control.Font = UIFont.FromName("Montserrat-Light", 10f);这一行
  • 如果找不到字体,那么UIFont.FromName("Montserrat-Light", 10f); 行将产生 null 或检查 Control != null 而不是 NewElement。另外,为什么要使用自定义渲染器?这可以通过样式完美完成:)
  • @GeraldVersluis 仅供参考:由于他将该字体应用于所有标签/条目,因此自定义渲染器比使用样式更快、更高效。

标签: xaml xamarin xamarin.forms xamarin.ios


【解决方案1】:

试试下面的代码。如果您没有在 XAML 中指定字体系列和大小,它将更新。现在您也可以在 XAML 中进行设置。

 public class CustomLabelRender : LabelRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);
        if (Control != null)
        {
            if (e.NewElement != null)
            {
                if (!String.IsNullOrEmpty(Element.FontFamily))
                    Control.Font = UIFont.FromName(this.Element.FontFamily, (nfloat)e.NewElement.FontSize);
            }
        }
    }

}

【讨论】:

  • 仍然给出同样的异常
  • 您能分享一下 Xaml 代码吗?您还必须在 info.plist 文件中添加字体。你添加了吗?
  • 是的,我已经在 info.plist 中添加了它,我没有在我的 xaml 中做一些特别的事情,只是添加了一个自定义渲染器
  • UIAppFontsMontserrat-Light.ttf 添加到 info.plist
  • 请在 info.plist 文件中添加此键 "UIDeviceFamily" 一次并检查。
【解决方案2】:

作为解决此问题的一种更简单的方法,我想推荐免费的开源 Forms9Patch NuGet 包的Label 元素和/或CustomFontEffect。它允许您将自定义字体作为嵌入式资源存储在 Xamarin.Forms 应用程序的跨平台项目(.NetStandard、PCL 或共享库)中,然后将该字体的嵌入式资源 ID 设置为任何 Xamarin.Forms 元素的 FontFamily具有FontFamily 属性。

var entry = new Xamarin.Forms.Entry {
    Text = "Xamarin.Forms.Entry element",
    FontFamily = "Forms9PatchDemo.Resources.Fonts.Pacifico.ttf"
};
entry.Effects.Add(Effect.Resolve("Forms9Patch.CustomFontEffect"));

var label = new Forms9Patch.Label
{
    Text = "Custom Font Text",
    FontFamily = "Forms9PatchDemo.Resources.Fonts.Pacifico.ttf"
}

完全披露:我是这个包的作者。

【讨论】:

    猜你喜欢
    • 2010-11-20
    • 1970-01-01
    • 2011-09-06
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 2017-04-17
    • 1970-01-01
    相关资源
    最近更新 更多