Question

In old RPGs, the dialogue text would type on screen, and if there was more than could fit on the page there'd be a ... and you'd press to NEXT to continue reading.

I've got a lot of this already working. What I'm stuck on is I need a block of text to programmatically know how to break itself up from page to page using the ...

Normally, the easy route would be to just specify in the dialogue where the breaks should be, but for this specific project I have to allow it to take in a large block of text, then break it into the correct sizes for each page.

Anyone have any thoughts on how to do this? Just counting characters won't work because the font won't be monospaced.

I was having a hell of a time trying to search for this. Found this, but it didn't answer my question.

Much appreciated!

Was it helpful?

Solution

One solution could be:

  1. separate all the words from the big text into an array
  2. go through of it and search for the boundaries based on textbox height

You can implement it eg.:

        CGFloat w = 200.0; // RPG textbox width. Get it from actual UI object.
        CGFloat h = 150.0; // RPG textbox height. Get it from actual UI object.
        NSArray *words = [yourRPGtext componentsSeparatedByString:@" "];
        NSString *cur_txt = [words objectAtIndex:0];
        int i = 1;
        RPG_txt_pages = [[NSMutableArray alloc] init];
        while (i < [words count]) {
            NSString *next_txt = [cur_txt stringByAppendingFormat:@" %@",[words objectAtIndex:i]];

            CGSize size = [next_txt sizeWithFont:yourRPGtextlable.font
                                    constrainedToSize:CGSizeMake(w, 99999)
                                    lineBreakMode:UILineBreakModeWordWrap];

            if (size.height > h) {
                cur_txt = [cur_txt stringByAppendingString:@"..."];
                [RPG_txt_pages addObject:cur_txt];
                cur_txt = [words objectAtIndex:i];
            } else {
                cur_txt = next_txt;
            }
            i++;
        }
        [RPG_txt_pages addObject:curText];

The key here is NSString's sizeWithFont method: here is the link to the docs.

IOS7 comment: sizeWithFont is deprecated you can use sizeWithAttributes. Here is an SO answer on this.

If you tell what IOS version are you using I'll modify this answer. Hope it helped!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top