NSArray中的换行符

时间:2015-03-31 11:45:47

标签: ios objective-c

我有一个数组,如何换行?

NSArray *stringsArray2 = @[
                      [NSString stringWithFormat:@"Distance is %f km",betweenDistance/1000],
                      [NSString stringWithFormat:@"Distance is %f km",betweenDistance3/1000],
                      [NSString stringWithFormat:@"Distance is %f km",betweenDistance4/1000]
                              ];
    NSString * combinedStuff = [stringsArray2 componentsJoinedByString:@"\n"];
    UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
    label3.text = combinedStuff;
    [self.view addSubview:label3];

5 个答案:

答案 0 :(得分:0)

我认为您可以创建字符串链接:

str= [NSString stringWithFormat:@"Distance is %f km \n Distance is %f km \nDistance is %f km ",betweenDistance/1000,betweenDistance3/1000,betweenDistance4/1000];

现在使用str字符串在Label上打印。

答案 1 :(得分:0)

替换这段代码:

NSString * combinedStuff = [stringsArray2 componentsJoinedByString:@"/n"];

有了这个:

NSString * combinedStuff = [stringsArray2 componentsJoinedByString:@"\n"];

答案 2 :(得分:0)

首先,你使用了错误的转义序列字符。

试试此代码

NSArray *stringsArray2 = @[
                               [NSString stringWithFormat:@"Distance is %f km",100.0],
                               [NSString stringWithFormat:@"Distance is %f km",200.0],
                               [NSString stringWithFormat:@"Distance is %f km",300.0]
                               ];
    NSString * combinedStuff = [stringsArray2 componentsJoinedByString:@"\n"];
    NSLog(@"combinedStuff %@",combinedStuff);
    UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 500, 300)];
    label3.text = combinedStuff;
    label3.numberOfLines = 0;
    label3.lineBreakMode = NSLineBreakByWordWrapping;
    [self.view addSubview:label3];

答案 3 :(得分:0)

NSString不会将

“\ n”解析为换行符,您必须使用“\\ n”来创建换行符。

答案 4 :(得分:0)

将numberOfLines设置为0以允许任意数量的行。

label.numberOfLines = 0;   

使用sizeWithFont:更新标签框以匹配文字大小。如果不这样做,您的文本将垂直居中或切断。

CGSize labelSize = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];
label.frame = CGRectMake(
label.frame.origin.x, label.frame.origin.y, 
label.frame.size.width, labelSize.height);