使用drawInRect:withAttributes对齐文本: [英] align text using drawInRect:withAttributes:
问题描述
在我的应用的iOS 5版本中,我有:
In the iOS 5 version of my app I had:
[self.text drawInRect: stringRect
withFont: [UIFont fontWithName: @"Courier" size: kCellFontSize]
lineBreakMode: NSLineBreakByTruncatingTail
alignment: NSTextAlignmentRight];
我正在升级iOS 7.上述方法已弃用。我现在正在使用 drawInRect:withAttributes:。 属性参数是NSDictionary对象。我可以使用以下内容获取 drawInRect:withAttributes:以使用前 font 参数:
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];
我要添加哪些键值对词典来获取 NSLineBreakByTruncatingTail 和 NSTextAlignmentRight ?
What key-value pairs do I add to dictionary to get NSLineBreakByTruncatingTail and NSTextAlignmentRight?
推荐答案
设置段落样式有一个键文本(包括换行模式,文本对齐等)。
There is one key to set the paragraph style of the text (including line breaking mode, text alignment, and more).
来自 docs :
NSParagraphStyleAttributeName
NSParagraphStyleAttributeName
此属性的值为一个 NSParagraphStyle
对象。使用此属性可将多个属性应用于一系列文本。如果未指定此属性,则字符串使用默认段落属性,由 NSParagraphStyle
的 defaultParagraphStyle
方法返回。 。
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];
这篇关于使用drawInRect:withAttributes对齐文本:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!