Sen*_*ful 4 objective-c word-wrap nsstring ios ios7
我注意到iOS 7引入了与文本布局相关的新类,例如NSLayoutManager,NSTextStorage和NSTextContainer.我如何使用这些来获取有关NSString上自动换行的信息?
例如,假设我有一个很长的NSString,我把它放在UILabel中.如果我在UILabel上启用多行,它将生成一个字符串,如下所示:
The quick brown fox jumps
over the lazy dog.
Run Code Online (Sandbox Code Playgroud)
这很好,但我无法访问代码中的换行符(例如,在jumps我希望它返回\n或类似之后的单词之后).我想知道断行发生在哪个字符索引处.我知道我们可以用CoreText做到这一点,但是因为我们在iOS 7中有这些新类,所以我想知道如何使用它们.
mat*_*att 13
例:
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]);
}];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2016 次 |
| 最近记录: |