I’m trying to split content of a rather long string into pages of content. Right now I’m doing this by character (500 characters per page) like this:
//Lets find out how many pages to make
int pageLength = 500; //how many characters per page
NSString *text = ((Story *) [self.story objectAtIndex:chapter]).content;
int NumberOfPages = (text.length/pageLength);
//NumberOfPages += 1;
//Build the Pages Array
NSMutableArray *pageStrings = [[NSMutableArray alloc] init];
for (int i = 0; i <= (NumberOfPages+1); i++)
{
if (i < NumberOfPages) {
//Load the text like normal
NSString *contentString = [[NSString alloc]initWithFormat:@"<html><head><style type=text/css>body {font-family: \"%@\"; font-size: %d;}</style></head><body><p>%@</p></body></htlm>",@"helvetica",20,[text substringWithRange:NSMakeRange(i*pageLength,pageLength)]];
[pageStrings addObject:contentString];
}
if (i == NumberOfPages) {
//on the last page, only load what's available
NSString *contentString = [[NSString alloc]initWithFormat:@"<html><head><style type=text/css>body {font-family: \"%@\"; font-size: %d;}</style></head><body><p>%@</p></body></htlm>",@"helvetica",20,[text substringWithRange:NSMakeRange(i*pageLength,(text.length-(i*pageLength)))]];
[pageStrings addObject:contentString];
}
if (i > NumberOfPages){
//add in a blank page on the end
NSString *contentString = [[NSString alloc]initWithFormat:@"<html><head><style type=text/css>body {font-family: \"%@\"; font-size: %d;}</style></head><body><p>%@</p></body></htlm>",@"helvetica",20,@"What do you do?"];
[pageStrings addObject:contentString];
}
}
pageContent = [[NSArray alloc] initWithArray:pageStrings];
This works great, but often ends up with words split in the middle. I’m trying to get it to split on the word instead. The string doesn’t have to be exactly 500 characters, just close to it.
If you want to do it “right” you should look at the NSString method:
You can intelligently enumerate text by words, lines, paragraphs, sentences, and character sequences.
Session 128, WWDC 2011, “Advanced Text Processing” has some good information about this.