私はTTTAttributedLabelを使用して、テキストを垂直方向に中央揃え ( と の両方TTTAttributedLabel
でUILabel
デフォルト)、1 行 (デフォルトも)、切り捨てられた末尾の改行で表示しています。
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;
上記のコードは以下をレンダリングします。
2 つのラベルの唯一の違いは、文字列の長さです。ご覧のとおり、2 番目の文字列は垂直方向の中央に配置されていません。