iOS 6中UILabel的多个字体大小的NSAttributedString行之间的等间距

时间:2013-06-16 22:16:00

标签: ios fonts uilabel nsattributedstring spacing

我有多行UILabel和属性文本。

文本中的所有行都是相同的字体,但每行的字体大小不同。

我正试图在每一行之间达到完全相同的垂直空间。

然而,显示的内容有可变空格。就好像是根据字体大小为字体添加了一个垂直边距。

CGFloat y = 0;

NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:@""];
NSArray *linesArray = [NSArray arrayWithObjects:@"One I\n",
                       @"Two I\n",
                       @"Three I\n",
                       @"Four I\n",
                       @"Five I\n", nil];

CGFloat fontSize = 10.0;

for(NSString *line in linesArray) {

    NSMutableAttributedString *attributedLine = [[NSMutableAttributedString alloc] initWithString:line];
    NSInteger stringLength=[line length];
    [attributedLine addAttribute:NSFontAttributeName
                              value:[UIFont fontWithName:@"TimesNewRomanPSMT" size:fontSize]
                              range:NSMakeRange(0, stringLength)];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 0.0f;
    paragraphStyle.alignment = NSTextAlignmentRight;
    [attributedLine addAttributes:@{ NSParagraphStyleAttributeName : paragraphStyle} range:NSMakeRange(0, stringLength)];


    [attString appendAttributedString:attributedLine];

    fontSize += 10.0;
}

UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor blackColor];
label.numberOfLines = 0;
label.attributedText = attString;
[label sizeToFit];
CGRect newFrame = label.frame;
newFrame.size.width = self.view.frame.size.width - 40;
newFrame.origin.y = y;
newFrame.origin.x = 0;
label.frame = newFrame;
[self.view addSubview:label];

对于我应该使用的代码的任何建议,以便它在每行文本之间根本不显示空格?

1 个答案:

答案 0 :(得分:3)

我一直在做类似的事情,所以也许你可以尝试这样的事情(输入浏览器,小心!):

NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setAlignment: NSTextAlignmentRight];
[style setLineSpacing:0];

for(NSString *line in linesArray) {
    NSMutableParagraphStyle *subStyle = [style mutableCopy];
    [subStyle setMaximumLineHeight:10]; // play around with this value <-----

    NSDictionary *attributes = 
    @{
      NSFontAttributeName : [UIFont fontWithName:@"TimesNewRomanPSMT" size:fontSize],
      NSParagraphStyleAttributeName : paragraphStyle,
    };

    [attString appendAttributedString:[[NSAttributedString alloc] initWithString:line attributes: attributes]];

    fontSize += 10.0;
}