如何使 TTTAttributedLabel 垂直对齐中心与截尾

How to make TTTAttributedLabel vertically align center with truncated tail

我正在使用 TTTAttributedLabel 显示一些垂直居中的文本(TTTAttributedLabelUILabel 中的默认值),单行(也是默认值)和截断的尾部断行.

TTTAttributedLabel *label1 = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(20.0, 40.0, 200.0, 60.0)];
label1.backgroundColor = [UIColor lightGrayColor];
label1.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
[self.view addSubview:label1];

TTTAttributedLabel *label2 = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(20.0, 120.0, 200.0, 60.0)];
label2.backgroundColor = [UIColor lightGrayColor];
label2.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
[self.view addSubview:label2];

NSString *shortString = @"This is a short string.";
NSString *longString = @"This is a somewhat longer string. In fact its really long. So long it takes up alot of space.";

NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:16.0]};

NSMutableAttributedString *shortAttributedString = [[NSMutableAttributedString alloc] initWithString:shortString attributes:attributes];
label1.attributedText = shortAttributedString;

NSMutableAttributedString *longAttributedString = [[NSMutableAttributedString alloc] initWithString:longString attributes:attributes];
label2.attributedText = longAttributedString;

以上代码呈现如下:

两个标签的唯一区别是字符串长度。如您所见,第二个字符串没有垂直居中。

根据 here 提出的类似问题,您需要将段落样式 lineBreakMode 设置为 NSLineBreakByTruncatingTail:

TTTAttributedLabel *label1 = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(20.0, 40.0, 200.0, 60.0)];
label1.backgroundColor = [UIColor lightGrayColor];
label1.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
[self.view addSubview:label1];

TTTAttributedLabel *label2 = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(20.0, 120.0, 200.0, 60.0)];
label2.backgroundColor = [UIColor lightGrayColor];
label2.verticalAlignment = TTTAttributedLabelVerticalAlignmentCenter;
[self.view addSubview:label2];

NSString *shortString = @"This is a short string.";
NSString *longString = @"This is a somewhat longer string. In fact its really long. So long it takes up alot of space.";

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;

NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:16.0],
                             NSParagraphStyleAttributeName: paragraphStyle};

NSMutableAttributedString *shortAttributedString = [[NSMutableAttributedString alloc] initWithString:shortString attributes:attributes];
label1.attributedText = shortAttributedString;

NSMutableAttributedString *longAttributedString = [[NSMutableAttributedString alloc] initWithString:longString attributes:attributes];
label2.attributedText = longAttributedString;