2011-07-05 10 views
0

我在加載到UITextView的.plist數組中有一段文字(4個句子)。任何方式分離UITextField中的文本?

默認情況下,它將文本顯示爲段落中文本的一大塊。我想知道是否有可能將此分裂?

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

有一種方法我可以搜索.,然後將線相應地分開?我只是手動編輯plist,但有數百個條目,因此很難做到。

回答

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

更新:OK,所以更詳細的未來通過。你可以使用正則表達式 - 但如果你不熟悉,學習曲線有點陡峭。否則,與其他答案一樣,查看列表。你需要照顧空格,空行等。下面的代碼片段不是很漂亮,但會完成這項工作。

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

謝謝馬修,但我怎樣才能添加行1,行2等? – Jon

+0

這將使多行,如果你有多個'.'s – PengOne

+0

雅,但我的意思是有實際的文字,說''第1行:「,」第2行:「等等 – Jon

0

試着製作一個循環遍歷數組,並將每一行添加到UITextView plus @「\ n」。

因此,像...:

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

或只是@更換點 「\ n」。

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

這可能會有所幫助.. !!

+0

嘿謝謝Dileep。但由於某些原因,它每次都會增加一條額外的行,所以當只有4行時,會有一個額外的'第5行'。 – Jon

+0

把這個條件放在for循環中if(![lines isEqualToString:@「」])。 –

+0

我該插入那一行嗎? – Jon

相關問題