CTFont with CTStringAttributes and NSMutableAttributedString crashes my app in xamarin

1.6k views Asked by At

I'm trying to create NSMutableAttributedString and set its properties with SetProperties method. But my app crashes with error,

MonoTouch.Foundation.MonoTouchException exception - NSInvalidArgumentException Reason: unrecognized selector sent to instance 0xc305d00.*

Code:

var richTask = new NSMutableAttributedString ("Random");
var fda = new CTFontDescriptorAttributes {
    FamilyName = "Courier",
    StyleName = "Bold",
    Size = 18f
};
var fd = new CTFontDescriptor (fda);
var font = new CTFont (fd, 0);

var attrs = new CTStringAttributes { Font = font };
var range = new NSRange (0, 3);
richTask.SetAttributes(attrs, range);

_label.AttributedText = richTask;

This code is in the GetCell method of UITableViewController. I want to be able to change font or color only of the first 3-4 letters of the string.

I figured out that if I eliminate Font component and set another property, for example, StrokeWidth, it works fine

var attrs = new CTStringAttributes { /*Font = font*/ StrokeWidth = 5f };

So it seems that font is initialized somewhat incorrect. Why is that? Why does it crash my app?

Thanks for advance!

1

There are 1 answers

0
jonathanpeppers On BEST ANSWER

Here is an example of using UIStringAttributes instead:

        string line1 = "Don't have Facebook?", line2 = "\nCreate or sign in with an alternate account";
        var attributedString = new NSMutableAttributedString(line1 + line2);

        attributedString.SetAttributes(new UIStringAttributes
        {
            Font = Theme.BoldSmallFont,
            ForegroundColor = Theme.LightGray,

        }.Dictionary, new NSRange(0, line1.Length));

        attributedString.SetAttributes(new UIStringAttributes
        {
            Font = Theme.RegularSmallFont,
            ForegroundColor = Theme.LightGray,

        }.Dictionary, new NSRange(line1.Length, line2.Length));

        _alternateSignIn.SetAttributedTitle(attributedString, UIControlState.Normal);

This is an example of setting two different fonts on a UIButton. Theme is my own static class, you can replace the color and font with your own.

You should be able to accomplish the same thing with UIStringAttributes as with CTStringAttributes. You might post a bug report to Xamarin for your case that crashes: http://bugzilla.xamarin.com

*NOTE: attributed string only works on iOS 6 and higher. This is when Apple added these APIs.