Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

ios - align text using drawInRect:withAttributes:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...