8

I am trying to put a Attributed string inside a NSTextField, which itself is inside an NSAlert Here is my code:

NSTextField *label1 = [[NSTextField alloc]initWithFrame:NSMakeRect(0, 23, 50, 20)];
[label1 setEditable:FALSE];
[label1 setAllowsEditingTextAttributes:TRUE];
[label1 setBezeled:FALSE];
label1.backgroundColor = [NSColor clearColor];
NSString *login = @"Username";
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:login];
NSString *boldFontName = [[NSFont boldSystemFontOfSize:12] fontName];
[attrString beginEditing];
NSRange ran = NSMakeRange(0, 8);
[attrString addAttribute:NSFontAttributeName
                   value:boldFontName
                   range:ran];

[attrString endEditing];
NSLog(@"%@",attrString);
[label1 setAttributedStringValue:attrString];
[alert setAccessoryView:label1];
[alert runModal];

However, as soon as [alert runModal] is called, my app crashes

"[__NSCFConstantString pointSize]: unrecognized selector sent to instance 0x7fff74035bb0"

I'm not sure why this is happening. It appears that it is related to the string, because as soon as i remove [alert setAccessoryView:label1] or give label1 a standard nsstring it works fine. Please help!

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
benjih555
  • 931
  • 2
  • 10
  • 25

2 Answers2

38

You have done right. But you did a small mistake. You have passed NSString as an attribute for NSFontAttributeName but it expects NSFont.

Try this.

    NSFont *boldFontName = [NSFont boldSystemFontOfSize:12];
[attrString beginEditing];
NSRange ran = NSMakeRange(0, 8);
[attrString addAttribute:NSFontAttributeName
                   value:boldFontName
                   range:ran];
Ramaraj T
  • 5,184
  • 4
  • 35
  • 68
1

The above answer is absolutely correct. I had a same crash which used to crash in iOS 7.0.3 & 7.0.4 only, and works perfectly in all other versions. After so much investigation, I came to know that @"HelveticaNeue-Italic" is not available in iOS 7.0.3 & 7.0.4 versions, so that I used to get above crash in those versions.

I have fixed the issue with below code :

self.headerFont = [UIFont fontWithName:@"HelveticaNeue-Italic" size:16.0f];
if (self.headerFont == nil) {
    self.headerFont = [UIFont fontWithName:@"HelveticaNeue" size:16.0f];
}