如何将字符串分为两部分
我正在解析我的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;
其实plist中保存您的字符串作为文本。所以如果你输入\ n它将其作为文本而不是linebreak。尽管如此,我只用plist打破了字符串。例如:如果你有一个字符串,你目前每月的收入是多少?你想从收入中挣脱。然后你可以写什么是你的,然后按alt +进入,并在新行中输入文本。
考虑使用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];
我不行。我必须使用这个视图来显示我们使用CoreText的内容。 – Ashutosh 2011-05-09 18:00:17
检查行分隔符是否实际上是\n
。它也可以是\r
。所以使用componentsSeparatedByString:@"\r\n"
可能会有所帮助。
请注意\ n在不同情况下的含义。
在这方面
NSArray * parts = [text componentsSeparatedByString:@"\n"];
\ n被解释为一个新行字符。
在你的plist \ n将被实际字符\和n
你可以使用选项,进入到换行符添加到plist中,然后使用以上或更好,但你的代码:
NSArray * parts = [text componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
或者,如果你想使用这个定制“\ n”分隔符,你可以使用
NSArray * parts = [text componentsSeparatedByString:@"\\n"];
那么,你的问题是什么?你有错误吗? – edc1591 2011-05-09 15:33:54
当你运行这段代码时发生了什么,你期望发生什么? – kubi 2011-05-09 15:34:55
我试图打破的字符串是“你什么时候想退休”,并且我希望它在“你”之后被打破所以我将它转换为“你什么时候想退休?”这样'你什么时候'出现在第一行,其余部分显示在下一行。 BU与此代码一切,包括\ n是在一行 – Ashutosh 2011-05-09 15:39:45