使用drawInRectalignment文本:withAttributes:

在我的应用程序的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

有一个键可以设置文本的段落样式(包括换行方式,文本alignment方式等)。

从文档 :

NSParagraphStyleAttributeName

这个属性的值是一个NSParagraphStyle对象。 使用此属性将多个属性应用于一系列文本。 如果不指定此属性,则string将使用默认段落属性,如NSParagraphStyledefaultParagraphStyle方法所返回的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]; 

代码是这样的:

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