在UITextField中分离文本的任何方法?

时间:2011-07-05 23:14:04

标签: iphone objective-c cocoa-touch

我在.plist数组中有一个段落(4个句子)的文本加载到UITextView中。

默认情况下,它会将文本显示为文本,作为段落中的一大块文本。我想知道是否可以拆分它?

如第1行:sdfafasfsafsa,第2行:asfdsafs,第3行:adfsfsdfsdfa等。

有没有办法可以搜索.,然后相应地分隔这些行?我只是手动编辑plist,但有数百个条目,所以不容易做到。

3 个答案:

答案 0 :(得分:3)

NSString* tidiedString = [sourceString stringByReplacingOccurrencesOfString:@"." withString:@"\n"];

更新:好的,所以会有更多详细信息。您可以使用正则表达式 - 但如果您不熟悉,则学习曲线有点陡峭。否则,与其他答案一样,通过列表。你需要处理空格,空行等。下面的代码片段并不漂亮,但可以完成这项工作。

NSString* sourceString = @"Hyperlinks can be great. They can also dilute your focus and tempt you into putting off what you most want to do. Here I chose to place links at the foot of the page to help you to make an active choice as to whether to surf or refocus your attention elsewhere.";

NSArray* arrayOfStrings = [sourceString componentsSeparatedByString:@"."];

NSMutableString* superString = [NSMutableString stringWithString:@""];

int lineCount = 1;
for (NSString* string in arrayOfStrings)
{
    if ([string length] < 1) continue;

    [superString appendFormat:@"Line %d: %@.\n", lineCount++, [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}

[superString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

[[self userEntry] setText:superString];

答案 1 :(得分:3)

NSArray *array = [sourceString componentsSeparatedByString:@"."];

NSMutableString *resultString= [[NSMutableString alloc] init];
int linecount=1;
for(NSString *lines in array)
{
    [resultString appendString:[NSString stringWithFormat:@"Line%i:%@\n",linecount++,lines]];
}

NSLog(@"resultString:%@",resultString);

这可能会有所帮助.. !!

答案 2 :(得分:0)

尝试创建一个遍历数组的循环,并将每行添加到UITextView加上@“\ n”。

就像......:

NSString *curText = txtView.text;
NSString *lineBreak = @"\n";
txtView.text=[NSString stringWithFormat:@"%@ + %@", curText, lineBreak];

或者只需用@“\ n”替换点。