本文介绍了Objective-c每10个字符换行(保持单词)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串,我将加载到TextField中,如何进行换行\ n每10个字符(包括空格和诸如此类)发生但不会转到下一行中间字...喜欢用最多10个字符包装文本?但我不只是包装在UITextField中我实际上需要输入\ n,因为它也将用于其他东西......(这对于iOS来说,如果这很重要)任何帮助都表示赞赏我真的被卡住了!

If I have a string that I am going to load into a TextField how can I make a line break \n occur every 10 characters (including spaces and whatnot) but not go to the next line mid-word... Like wrap the text with a max of 10 characters? But I'm not just wrapping in a UITextField I actually need the \n's entered because it will be used in something else as well... (This is for iOS if that matters) any help is appreciated I'm really stuck!

推荐答案

您可能希望在循环中使用NSScanner来组合这类事物,但要弄清楚精确您需要准确地弄清楚您希望它如何工作的算法。以下是您需要回答的问题:

You might want to make use of NSScanner in a loop to put together this kind of thing, but to figure out the precise algorithm you'd need to clarify exactly how you want it to work. Here are questions that you would need to answer:


  1. 如果单词之间多个空格的序列被折叠为单个空格包装文本的目的,还是应该将5个连续的空格序列计算为每行10个字符的5个字符?我假设您希望折叠多个空格而不是保留。

  2. 如果您有一个大于10个字符的单个单词,您希望它如何工作?你希望它最终得到一个大于10个字符的行,或者你更喜欢插入换行符并在那种情况下强制中间行换行?我假设您希望允许超过10个字符的单词超出10个字符的限制。

关于您的问题的这些假设我会这样编码:

With these assumptions about your problem in mind, I would code it like this:

NSMutableString *resultString = [[NSMutableString alloc] init];
NSMutableString *currentLine = [[NSMutableString alloc] init];
NSScanner *scanner = [NSScanner scannerWithString:sourceString];
NSString *scannedString = nil;
while ([scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString: &scannedString]) {
    if ([currentLine length] + [scannedString length] <= 10) {
        [currentLine appendFormat:@"%@ ", scannedString];
    }
    else if ([currentLine length] == 0) { // Newline but next word > 10
        [resultString appendFormat:@"%@\n", scannedString];
    }
    else { // Need to break line and start new one
        [resultString appendFormat:@"%@\n", currentLine];
        [currentLine setString:[NSString stringWithFormat:@"%@ ", scannedString]];
    }
    [scanner scanCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString:NULL];
}

这篇关于Objective-c每10个字符换行(保持单词)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 03:40