使用drawInRect:withAttributes:对齐文本

47

在我的应用的 iOS 5 版本中,我有:

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

我正在升级iOS 7。上面的方法已经被弃用了。我现在使用drawInRect:withAttributes:attributes参数是一个NSDictionary对象。我可以使用以下方法使得drawInRect:withAttributes:适用于先前的font参数:

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

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

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

我该向字典中添加哪些键-值对,才能获得NSLineBreakByTruncatingTailNSTextAlignmentRight

2个回答

141

有一个关键点可以设置文本的段落样式(包括换行模式、文本对齐等)。

来自文档

NSParagraphStyleAttributeName

这个属性的值是一个 NSParagraphStyle 对象。使用此属性将多个属性应用于一组文本。如果未指定此属性,则字符串使用默认段落属性,由 NSParagraphStyledefaultParagraphStyle 方法返回。

因此,您可以尝试以下内容:

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

2
你是怎么发现这个的?+1 - ViruMax
虽然我想不出更短的变体,但这肯定有效,但似乎为了添加一些调整而需要付出很多努力! - Desh__
如何使字符串多行? - Olcay Ertaş

5
代码走这样:
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];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接