2011-05-09 64 views
1

我正在解析我的plist中的一個字符串,並試圖將它分解爲兩部分,以按照中斷在兩行或三行中顯示它們。如何將字符串分爲兩部分

NSArray * parts = [text componentsSeparatedByString:@"\n"]; // this text is coming from plist. 
int nthLine = 0; 
for(NSString *str in parts) 
{ 

CGRect outerFrame = CGRectMake(frame1.origin.x, frame1.origin.y + 45*nthLine, frame1.size.width, 45); 

SFNDoorStyledView * question = [[SFNDoorStyledView alloc]initWithFrame:outerFrame]; 
question.backgroundColor = [UIColor clearColor]; 
question.tag = 2; 
[question drawString:text inRect:CGRectMake(0,0,500,150) usingFontNamed:@"Futura-Bold" size:40.0 lineSpacing:40.0 kernValue:-3.0 color:@"#7d7066"]; 
[self.view addSubview:question]; 
} 
nthLine = nthLine +1; 
+0

那麼,你的問題是什麼?你有錯誤嗎? – edc1591 2011-05-09 15:33:54

+0

當你運行這段代碼時發生了什麼,你期望發生什麼? – kubi 2011-05-09 15:34:55

+0

我試圖打破的字符串是「你什麼時候想退休」,並且我希望它在「你」之後被打破所以我將它轉換爲「你什麼時候想退休?」這樣'你什麼時候'出現在第一行,其餘部分顯示在下一行。 BU與此代碼一切,包括\ n是在一行 – Ashutosh 2011-05-09 15:39:45

回答

0

其實plist中保存您的字符串作爲文本。所以如果你輸入\ n它將其作爲文本而不是linebreak。儘管如此,我只用plist打破了字符串。例如:如果你有一個字符串,你目前每月的收入是多少?你想從收入中掙脫。然後你可以寫什麼是你的,然後按alt +進入,並在新行中輸入文本。

0

考慮使用UILabel牽你的文字,你可以動態的大小基於字符串本身。不需要在字符串中包含\n。只需根據您需要的寬度尺寸/約束您的標籤,並根據其他屬性(如字體和字體大小)爲您計算高度。這是一個代表性的片段。

// Size the label based on the font and actual text 
UILabel *l = [[[UILabel alloc] initWithFrame:CGRectMake(10, 5, 300, 50)] autorelease]; 
l.font = [UIFont boldSystemFontOfSize:14.0]; 
l.lineBreakMode = UILineBreakModeWordWrap; 
l.textAlignment = UITextAlignmentCenter; 
l.numberOfLines = 0; // Allow for as many lines as needed 
l.backgroundColor = [UIColor clearColor]; 
CGSize constraintSize = CGSizeMake(300, MAXFLOAT); 
CGSize labelSize = [l.text sizeWithFont:l.font 
     constrainedToSize:constraintSize 
     lineBreakMode:UILineBreakModeWordWrap]; 
CGRect frame = l.frame; 
frame.size = labelSize; 
// Center it 
frame.origin.x = floor((320.0 - labelSize.width)/2.0); 
l.frame = frame; 

[v addSubview:l]; 
+0

我不行。我必須使用這個視圖來顯示我們使用CoreText的內容。 – Ashutosh 2011-05-09 18:00:17

0

檢查行分隔符是否實際上是\n。它也可以是\r。所以使用componentsSeparatedByString:@"\r\n"可能會有所幫助。

3

請注意\ n在不同情況下的含義。

在這方面

NSArray * parts = [text componentsSeparatedByString:@"\n"]; 

\ n被解釋爲一個新行字符。

在你的plist \ n將被實際字符\和n

你可以使用選項,進入到換行符添加到plist中,然後使用以上或更好,但你的代碼:

NSArray * parts = [text componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]; 

或者,如果你想使用這個定製「\ n」分隔符,你可以使用

NSArray * parts = [text componentsSeparatedByString:@"\\n"]; 
相關問題