How to use NSString drawInRect to center text?
Martins answer is pretty close, but it has a few small errors. Try this:
NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
[style setAlignment:NSCenterTextAlignment];
NSDictionary *attr =
[NSDictionary dictionaryWithObject:style
forKey:NSParagraphStyleAttributeName];
[myString drawInRect:someRect withAttributes:attr];
[style release];
You'll have to create a new NSMutableParagraphStyle
(instead of using the default paragraph style as Martin suggested) because [NSMutableParagraphStyle defaultParagraphStyle]
returns an NSParagraphStyle
, which doesn't have the setAlignment method. Also, you don't need the string @"NSParagraphStyleAttributeName"
—just NSParagraphStyleAttributeName
.
This works for me:
CGRect viewRect = CGRectMake(x, y, w, h);
UIFont* font = [UIFont systemFontOfSize:15];
CGSize size = [nsText sizeWithFont:font
constrainedToSize:viewRect.size
lineBreakMode:(UILineBreakModeWordWrap)];
float x_pos = (viewRect.size.width - size.width) / 2;
float y_pos = (viewRect.size.height - size.height) /2;
[someText drawAtPoint:CGPointMake(viewRect.origin.x + x_pos, viewRect.origin.y + y_pos) withFont:font];
Vertical alignment you'll have to do yourself ((height of view + height of string)/2). Horizontal alignment you can do with:
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
style.alignment = NSTextAlignmentCenter;
NSDictionary *attr = [NSDictionary dictionaryWithObject:style forKey:NSParagraphStyleAttributeName];
[myString drawInRect:someRect withAttributes:attr];
This works for me for horizontal alignment
[textX drawInRect:theRect
withFont:font
lineBreakMode:UILineBreakModeClip
alignment:UITextAlignmentCenter];