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:使用这个来处理前一个字体参数:

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

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

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

我将哪些键值对添加到字典以获取NSLineBreakByTruncatingTailNSTextAlignmentRight

4

2 回答 2

141

一键设置文本的段落样式(包括换行模式、文​​本对齐方式等)。

来自文档

NSParagraphStyleAttributeName

该属性的值是一个NSParagraphStyle对象。使用此属性可将多个属性应用于一系列文本。如果不指定此属性,则字符串使用默认的段落属性,由 的defaultParagraphStyle方法返回NSParagraphStyle

因此,您可以尝试以下方法:

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];
于 2013-09-22T23:54:36.040 回答
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];
于 2016-03-05T14:32:15.813 回答