问题描述
我注意到 iOS 7 引入了与文本布局相关的新类,例如 NSLayoutManager、NSTextStorage 和 NSTextContainer.我如何使用这些来获取有关 NSString 上自动换行的信息?
I noticed that iOS 7 introduces new classes related to text layout such as NSLayoutManager, NSTextStorage, and NSTextContainer. How can I use these in order to get information about word wrapping on an NSString?
例如,假设我有一个很长的 NSString 放在 UILabel 中.如果我在 UILabel 上启用多行,它会产生一个如下所示的字符串:
For example, say I have a long NSString which I put in a UILabel. If I enable multiple lines on the UILabel, it would produce a string such as the following:
The quick brown fox jumps
over the lazy dog.
那太好了,但我无法访问代码中的换行符(例如,在 jumps
这个词之后,我希望它返回 或类似的东西).我想知道换行符发生在哪些字符索引处.我知道我们可以用 CoreText 做到这一点,但由于我们在 iOS 7 中有这些新类,我想知道我们如何才能改用它们.
That's great, but I can't access the line breaks in code (e.g. after the word jumps
I would want it to return or something similar). I would want to know at which character indexes the line breaks occur. I know we can do this with CoreText, but since we have these new classes in iOS 7, I was wondering how we can use them instead.
推荐答案
示例:
CGFloat maxWidth = 150;
NSAttributedString *s =
[[NSAttributedString alloc]
initWithString:@"The quick brown fox jumped over the lazy dog."
attributes:@{NSFontAttributeName:[UIFont fontWithName:@"GillSans" size:20]}];
NSTextContainer* tc =
[[NSTextContainer alloc] initWithSize:CGSizeMake(maxWidth,CGFLOAT_MAX)];
NSLayoutManager* lm = [NSLayoutManager new];
NSTextStorage* tm = [[NSTextStorage alloc] initWithAttributedString:s];
[tm addLayoutManager:lm];
[lm addTextContainer:tc];
[lm enumerateLineFragmentsForGlyphRange:NSMakeRange(0,lm.numberOfGlyphs)
usingBlock:^(CGRect rect, CGRect usedRect,
NSTextContainer *textContainer,
NSRange glyphRange, BOOL *stop) {
NSRange r = [lm characterRangeForGlyphRange:glyphRange actualGlyphRange:nil];
NSLog(@"%@", [s.string substringWithRange:r]);
}];
这篇关于如何使用新的 iOS 7 API 获取自动换行信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!