0

我有一个带有属性文本的多行 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];

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

4

1 回答 1

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;
}
于 2013-06-27T12:51:52.730 回答