I am trying to draw a string with new lines (\n) in a cocoa NSView with center alignment. For example if my string is:
NSString * str = @"this is a long line \n and \n this is also a long line";
I would like this to appear somewhat as:
this is a long line
and
this is also a long line
Here is my code inside NSView drawRect method:
NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setAlignment:NSCenterTextAlignment];
NSDictionary * attributes = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
NSString * mystr = @"this is a long line \n and \n this is also a long line";
[mystr drawAtPoint:NSMakePoint(20, 20) withAttributes:attributes];
It still draws the text with left alignment. What is wrong with this code?
The documentation for
-[NSString drawAtPoint:withAttributes:]states the following:Since the width is unlimited, that method discards paragraph alignment and always renders the string left-aligned.
You should use
-[NSString drawInRect:withAttributes:]instead. Since it accepts a frame and a frame has a width, it can compute center alignments. For instance:Note that you’re leaking
paragraphStylein your original code.