Guven
Guven

Reputation: 2310

NSString drawInRect draws blank if first character is a new line character (\n)

I just noticed this behaviour. I am drawing a PDF with the following call:

[string drawInRect:renderingRect
              withFont:font
         lineBreakMode:NSLineBreakByWordWrapping
             alignment:alignment];

Everything is fine except when the first character of string is a new line (\n) character. For example:

[@"Hello hello" drawInRect:renderingRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:alignment]; // Draws "Hello hello"

[@"\nHello hello" drawInRect:renderingRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:alignment]; // Draws nothing

Is there anything am I missing? It seems a bit odd to me that the method wouldn't print anything if the first character is a new line.

Also, (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode has no problems when the first character is a new line character. It does the size estimation with no problems.

Upvotes: 1

Views: 636

Answers (2)

Guven
Guven

Reputation: 2310

I have started compiling the app with iOS7 and the problem doesn't happen anymore. So, it must have happened due to following configuration:

  • Building the app with iOS6
  • Running the app with iOS7 devices.

Upvotes: 1

Greg
Greg

Reputation: 25459

If you use text encoding the two characters: \n will be draw but I believe you want to put line break instead. Try this code it works for me:

NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:[NSFont fontWithName:@"Helvetica" size:22], NSFontAttributeName,[NSColor blackColor], NSForegroundColorAttributeName, nil];

NSAttributedString *text=[[NSAttributedString alloc] initWithString:@"Hello hello" attributes: attr];

NSSize attrSize = [text size];
[text drawAtPoint:NSMakePoint(X, Y)];

I think you can replace drawAtPoint:method with some method to takes rectangle as a parameter.

Upvotes: 0

Related Questions