LoginSignup
4
4

More than 5 years have passed since last update.

UILabelで行間を調節したい。ただし、折り返しの場合は行間はデフォルトで。

Posted at

UILabelの行間を調整する記事はよく見かけるのですが、行間を調整しつつ、折り返しの場合だけは行間をデフォルトで、ということがやりたかったです。

行間を調整したいだけならこちらの方法が使えます。
http://qiita.com/Jacminik/items/21f87aadc3a4363b9802

ただ、当然のことながら折り返しの時まで行間が調整されてしまいます。

色々と考えた結果、フォントサイズの小さい改行を行間の代わりに使うようにしてみました。

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
NSArray *texts = [text componentsSeparatedByString:@"\n"];
int i = 0;
for (NSString *text in texts) {
    if (i > 0) {
        // 行間用の改行を追加
        NSMutableAttributedString *lf = [[NSMutableAttributedString alloc] initWithString:@"\n\n"];
        UIFont *font = [UIFont systemFontOfSize:4.0f];
        [lf addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, lf.length)];
        [attributedString appendAttributedString:lf];
    }

    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
    UIFont *font = [UIFont systemFontOfSize:12.0f];
    [attributedText addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attributedText.length)];
    [attributedString appendAttributedString:attributedText];

    i++;
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4