我使用TTTAttributedLabel显示一些以垂直为中心的文本(在TTTAttributedLabel和UILabel中都是默认的),只有一行(也是默认的)和截短的尾行中断。
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;上述代码呈现如下内容:

这两个标签的唯一区别是字符串长度。如您所见,第二个字符串不是垂直居中的。
发布于 2015-08-24 07:00:56
根据向这里提出的类似问题,您需要将段落样式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;https://stackoverflow.com/questions/32175946
复制相似问题