开发者

How to break a string into two parts

I am开发者_StackOverflow中文版 parsing a string from my plist and trying to break it into two parts to display them in two or three lines as per the break.

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;


Be careful what \n means in different contexts.

In this context

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

\n is interpreted as a newline character.

In your plist \n will be the actual characters \ and n

You could use option-enter to add the newline character to the plist and then use your code above or better yet:

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

Or if you want to use this custom '\n' delimiter you could use

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


Consider using a UILabel to hold your text, which you can size dynamically based on the string itself. No need to include \n in the string. Just size/constrain your label to the width you need, and the height will be calculated for you based on other attributes like font and font size. Here's a representative snippet.

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


Check if the line separator is actually \n. It could also be \r. So using componentsSeparatedByString:@"\r\n" might help.


Actually plist saves your string as a text. SO if you enter \n it takes it as a text and not as linebreak. In spite of doing it i break the string in plist only. For ex: if you have a string , What is your current income monthly? and you want to break it from income. Then you can write What is your and then press alt+enter and enter the text in new line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜