在iOS 7中NSLineBreakMode的等效字符串绘制方法是什么?

时间:2013-10-05 12:19:04

标签: ios nsstring uikit nsattributedstring

有一种方法

- (CGSize)drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment;

我现在必须替换iOS 7.我得到了

NSDictionary *attributes = @{NSFontAttributeName: font};
[self drawInRect:rect withAttributes:attributes];

但如何指定像换行一样的换行模式?我搜索了归因字符串绘制符号的文档但没有提到换行模式。这自动地总是自动换行吗?

2 个答案:

答案 0 :(得分:52)

您需要创建一个段落样式。

NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];

NSDictionary *attributes = @{NSFontAttributeName: font, NSParagraphStyleAttributeName: style};
[self drawInRect:rect withAttributes:attributes];

更多信息: https://developer.apple.com/documentation/uikit/nsparagraphstyle?language=objc

答案 1 :(得分:7)

在swift:

let style = NSMutableParagraphStyle()
style.lineBreakMode = .ByWordWrapping

let attributes: [String: AnyObject] = [
   NSFontAttributeName: font,
   NSParagraphStyleAttributeName: style
]