30

有一种方法

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

我现在必须为 iOS 7 替换它。我做到了

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

但是如何指定换行等换行模式?我搜索了属性字符串绘图符号的文档,但没有提到换行模式。这是否总是自动换行?

4

2 回答 2

58

您需要创建段落样式。

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

于 2013-10-05T12:38:21.403 回答
8

在 Swift 5 中:

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

let attributes: [NSAttributedString.Key: Any] = [
   .font: font,
   .paragraphStyle: style
]
于 2016-04-07T08:21:27.170 回答