What is the equivalent of NSLineBreakMode in iOS 7 attributed strings drawing methods?

心不动则不痛 提交于 2019-11-29 01:42:10

问题


There was a method

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

which I must replace now for iOS 7. I get as far as

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

but how to specify the line break mode like word wrap? I searched documentation of Attributed string drawing symbols but no mention of line break mode. Is this automartically always word-wrap?


回答1:


You need to create a paragraph style.

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

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

More information here: https://developer.apple.com/documentation/uikit/nsparagraphstyle?language=objc




回答2:


In Swift 5:

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

let attributes: [NSAttributedString.Key: Any] = [
   .font: font,
   .paragraphStyle: style
]


来源:https://stackoverflow.com/questions/19197709/what-is-the-equivalent-of-nslinebreakmode-in-ios-7-attributed-strings-drawing-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!