Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

objective c - How do I get word wrap information with the new iOS 7 APIs?

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?

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Example:

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]);
}];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...