简体   繁体   中英

get text in NSTextContainer

I have a NSOrderedSet of paragraphs with NSString content. Looping through all, a large string is created and given NSTextStorage. But with that all the paragraphs are lost.

The code below allows me to count the pages and present the content in pages. But I'd like to separate the content in paragraphs and know when a user taps on a particular paragraph.

How can I use NSTextStorage to display the content not as one single large string but as a collection of smaller text blocks? Note: I'm using a UIPageViewController to display the content so I also need to know the number of paragraphs per page.

NSString *content = @"";
for (TWParagraph *paragraph in self.bookParagraphs)
{
    TWTextBlock *textBlock = paragraph.hasTextBlock.firstObject;
    content = [content stringByAppendingString:textBlock.textContent];
}

NSTextStorage *localTextStorage = [[NSTextStorage alloc] initWithString:content];
NSLayoutManager *localLayoutManager = [NSLayoutManager new];
NSTextContainer *localTextContainer = [self createTextContainer];
localLayoutManager.delegate = self;
[localTextStorage addLayoutManager:localLayoutManager];
[localLayoutManager addTextContainer:localTextContainer];

[localLayoutManager ensureLayoutForTextContainer:localTextContainer];


self.numberOfPages = [[localLayoutManager textContainers] count];

Thanks.

I could not find a solution using NSTextContainer. In the end I solved it by splitting up the text into cells in an UITableView.

The height of each cell is calculated based on the amount of text it should contain.

- (CGRect) calculateRectSize: (TWTextBlock *) textBlock forAttributes:(NSDictionary *) customAttributes {
    CGSize constraintSize = CGSizeMake(self.tableViewRect.size.width - 10.0f, 400);
    return [[textBlock textContent] boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:customAttributes context:nil];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM