Xamarin.ios 无法在未引发System.NullReferenceException的情况下对控件进行子类化

Xamarin.ios 无法在未引发System.NullReferenceException的情况下对控件进行子类化,xamarin.ios,interface-builder,xamarin,xib,Xamarin.ios,Interface Builder,Xamarin,Xib,我正在尝试在我的MonoTouch iOS应用程序中将UILabel子类化,因为我被告知这是应用自定义字体最可靠的方法。我已将字体添加到我的Resources文件夹中,并将条目添加到Info.plist文件中,但是在使用IB中指定的子类运行应用程序时,我遇到了一致的错误。下面是代码: OpenSansRegularLabel.cs [注册开放标准标签] 公共分部类OpenSansRegularLabel:CustomFontLabel { 公共OpenSansRegularLabel:baseO

我正在尝试在我的MonoTouch iOS应用程序中将UILabel子类化,因为我被告知这是应用自定义字体最可靠的方法。我已将字体添加到我的Resources文件夹中,并将条目添加到Info.plist文件中,但是在使用IB中指定的子类运行应用程序时,我遇到了一致的错误。下面是代码:

OpenSansRegularLabel.cs

[注册开放标准标签] 公共分部类OpenSansRegularLabel:CustomFontLabel { 公共OpenSansRegularLabel:baseOpenSans常规,10f{} } CustomFontLabel.cs

公共类CustomFontLabel:UILabel { 私有只读字符串_fontName; 私有只读浮点_pointSize; 公共CustomFontLabelstring fontName,浮点大小 { _fontName=fontName; _pointSize=pointSize; } 公共覆盖无效AwakeFromNib { base.AwakeFromNib; Font=UIFont.FromName\u fontName,\u pointSize; } } 在XCode中的XIB文件中,我在UILabel上将自定义类指定为OpenSansRegularLabel。如上所述,每次AppDelegate.cs中都会出现错误:

窗口; UIViewController视图控制器; 公共覆盖bool finishedLaunchingUI应用程序应用程序,NSDictionary选项 { 窗口=新UIWindowUIScreen.MainScreen.Bounds; viewController=新用户指南主屏幕; window.RootViewController=视图控制器; window.MakeKeyAndVisible;//此处引发错误:System.NullReferenceException 返回true; }
这似乎是一个需要解决的简单问题,我觉得我遗漏了一些显而易见的东西。谢谢您的帮助。

原来这是我自己的错误-我没有包括UILabel所需的所有构造函数。如果将来对任何人都有帮助,我将在下面提供最终工作代码:

CustomFontLabel.cs


使用属性字符串来定制标签的字体样式会更容易。然后,不使用文本属性,只使用AttributedText属性设置文本

以下是一个例子:

NSMutableAttributedString属性字符串; NSRange范围1; 使用attrString=new NSMutableAttributedStringString.Format{0}*,label.Text { range1=新的NSRange 0,attrString.Length; attrString.AddAttribute UIStringAttribute UIStringAttributeKey.ForegroundColor、UIColor.FromRGB199、90、49、range1; attrString.AddAttribute UIStringAttributeKey.Font,UIFont.FromNameHelveticaNeue-Bold,12f,范围1; label.attributeText=attrString; };
public class CustomFontLabel : UILabel
{
    public string FontName { get; set; }

    public CustomFontLabel() {}
    public CustomFontLabel(IntPtr ptr) : base(ptr) { }
    public CustomFontLabel(NSCoder coder) : base(coder) { }

    public override void AwakeFromNib()
    {
        Font = UIFont.FromName(FontName, Font.PointSize);
    }
}