Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

align text using drawInRect:withAttributes:

Tags:

ios

nsstring

ios7

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?

like image 926
StephenAshley.developer Avatar asked Sep 22 '13 19:09

StephenAshley.developer


2 Answers

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];
like image 106
Hejazi Avatar answered Oct 20 '22 22:10

Hejazi


The code is going that way:

CGRect textRect = CGRectMake(x, y, length-x, maxFontSize);
UIFont *font = [UIFont fontWithName:@"Courier" size:maxFontSize];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;


   paragraphStyle.alignment = NSTextAlignmentRight;
    NSDictionary *attributes = @{ NSFontAttributeName: font,
                                  NSParagraphStyleAttributeName: paragraphStyle,
                                  NSForegroundColorAttributeName: [UIColor whiteColor]};
[text drawInRect:textRect withAttributes:attributes];
like image 41
Darius Miliauskas Avatar answered Oct 20 '22 21:10

Darius Miliauskas