align text using drawInRect:withAttributes:

StephenAshley.developer picture StephenAshley.developer · Sep 22, 2013 · Viewed 33.6k times · Source

In the iOS 5 version of my app I had:

[self.text drawInRect: stringRect
             withFont: [UIFont fontWithName: @"Courier" size: kCellFontSize]
        lineBreakMode: NSLineBreakByTruncatingTail
            alignment: NSTextAlignmentRight];

I'm upgrading for iOS 7. The above method is deprecated. I'm now using drawInRect:withAttributes:. The attributes parameter is an NSDictionary object. I can get drawInRect:withAttributes: to work for the former font parameter using this:

      UIFont *font = [UIFont fontWithName: @"Courier" size: kCellFontSize];

      NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: font, NSFontAttributeName,
                                  nil];

      [self.text drawInRect: stringRect
             withAttributes: dictionary];

What key-value pairs do I add to dictionary to get NSLineBreakByTruncatingTail and NSTextAlignmentRight?

Answer

Hejazi picture Hejazi · Sep 23, 2013

There is one key to set the paragraph style of the text (including line breaking mode, text alignment, and more).

From docs:

NSParagraphStyleAttributeName

The value of this attribute is an NSParagraphStyle object. Use this attribute to apply multiple attributes to a range of text. If you do not specify this attribute, the string uses the default paragraph attributes, as returned by the defaultParagraphStyle method of NSParagraphStyle.

So, you can try the following:

UIFont *font = [UIFont fontWithName:@"Courier" size:kCellFontSize];

/// Make a copy of the default paragraph style
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
/// Set text alignment
paragraphStyle.alignment = NSTextAlignmentRight;

NSDictionary *attributes = @{ NSFontAttributeName: font,
                    NSParagraphStyleAttributeName: paragraphStyle };

[text drawInRect:rect withAttributes:attributes];