首页 文章

在xamarin.iOS中的标签上应用自定义字体

提问于
浏览
0

我想在所有标签和条目中应用蒙特塞拉特 - 莱特字体样式,我是通过制作控件渲染器来实现的 . EntryRenderer工作正常,但LabelRenderer给出了带有消息的ArgumentNullException:Value不能为null .

[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);

        }
    }
}
}

2 回答

  • 0

    试试下面的代码 . 如果您未在XAML中指定font-family和size,它将更新 . 现在您也可以在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);
                }
            }
        }
    
    }
    
  • 0

    作为解决此问题的更简单方法,我想推荐免费的开源Forms9Patch NuGet包的 Label 元素和/或 CustomFontEffect . 它允许您将自定义字体作为嵌入式资源存储在Xamarin.Forms应用程序's cross platform project (.NetStandard, PCL, or Shared Library) and then set that font'的嵌入式资源ID中,作为 FontFamily ,用于具有 FontFamily 属性的任何Xamarin.Forms元素 .

    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"
    }
    

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

相关问题