拆分字符串转换成Objective-C中的内容页 [英] Split a string into pages of content in Objective-C

查看:217
本文介绍了拆分字符串转换成Objective-C中的内容页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个相当长的字符串内容分割成页的内容。现在我用字符(每页500字)这样做的:

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

这个伟大的工程,但往往在中间分开的话结束了。我试图让它上的字,而不是分裂。该字符串并不一定是完全500个字符,只要靠近它。

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.

推荐答案

如果你想这样做正确的,你应该看的NSString方法:

If you want to do it "right" you should look at the NSString method:

- (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block

您可以通过智能字数,行数,段落,句子和字符序列枚举文字。

You can intelligently enumerate text by words, lines, paragraphs, sentences, and character sequences.

会话128,WWDC 2011年,高级文本处理有对此一些有用的信息。

Session 128, WWDC 2011, "Advanced Text Processing" has some good information about this.

这篇关于拆分字符串转换成Objective-C中的内容页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆