2014-01-09 46 views
-1

我試圖在我的MonoTouch iOS應用程序中繼承UILabel,因爲我已被告知這是應用自定義字體最可靠的方法。我加入的字體我Resources文件夾,並添加條目到Info.plist文件,但是我正在與IB指定的子類的應用程序時獲得一致的錯誤。下面的代碼:無法在沒有引發System.NullReferenceException的情況下繼承控件

OpenSansRegularLabel.cs

[Register("OpenSansRegularLabel")] 
public partial class OpenSansRegularLabel : CustomFontLabel 
{ 
    public OpenSansRegularLabel() : base("OpenSans-Regular", 10f) {} 
} 

CustomFontLabel.cs

public class CustomFontLabel : UILabel 
{ 
    private readonly string _fontName; 
    private readonly float _pointSize; 

    public CustomFontLabel(string fontName, float pointSize) 
    { 
     _fontName = fontName; 
     _pointSize = pointSize; 
    } 

    public override void AwakeFromNib() 
    { 
     base.AwakeFromNib(); 
     Font = UIFont.FromName(_fontName, _pointSize); 
    } 
} 

在我的XIB文件XCode中我已指定自定義類作爲OpenSansRegularLabel我的UILabel。如前所述,雖然每次都讓我有錯誤AppDelegate.cs

UIWindow window; 
UIViewController viewController; 

public override bool FinishedLaunching(UIApplication app, NSDictionary options) 
{ 
    window = new UIWindow(UIScreen.MainScreen.Bounds); 

    viewController = new UserGuideMainScreen(); 
    window.RootViewController = viewController; 
    window.MakeKeyAndVisible(); // Error thrown here: System.NullReferenceException 

    return true; 
} 

這似乎是這樣一個簡單的問題要解決,我覺得我失去了一些東西明顯。謝謝你的幫助。

回答

0

原來,這是我自己的錯 - 我沒有包括所有必要的構造函數UILabel。它應該有助於在未來的人,我會包括下面的最終工作代碼:

CustomFontLabel.cs

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); 
    } 
} 
0

這將是更容易使用歸因字符串自定義的字體樣式標籤。然後,不要使用Text屬性,只需使用AttributedText屬性來設置文本。

下面是一個例子:

NSMutableAttributedString attrString; 
NSRange range1; 

using (attrString = new NSMutableAttributedString(String.Format ("{0}*", label.Text))) 
{ 
    range1 = new NSRange (0, attrString.Length); 
    attrString.AddAttribute (UIStringAttributeKey.ForegroundColor, UIColor.FromRGB(199, 90, 49), range1); 
    attrString.AddAttribute (UIStringAttributeKey.Font, UIFont.FromName("HelveticaNeue-Bold", 12f), range1); 
    label.AttributedText = attrString;    
}; 
相關問題