COMPANY SERVICE STAFF BLOG NEWS CONTACT

STAFF BLOG

スタッフブログ

TECHNICAL

テクログ

2014.05.20

Objective-C | 複数行のUILabelの行間を変える

テクログ

Mac,iPhone,Objective-C 全て利用歴5ヶ月の新米プログラマーが送る

自分が使って役立ったmethod?集

シリーズ第七弾です。

前回のUILabelの高さを動的に変えるために複数行入力した際に行数に合わせて枠が伸びるようにしたあと、さらに行の隙間を調整したい時にどうぞ。

common.h

+ (void)labelSpacing:(UILabel *)label height:(float)height inText:(NSString *)inText;

common.m

// 複数行あるUILable の高さを変更
+ (void)labelSpacing:(UILabel *)label height:(float)height inText:(NSString *)inText
{

    // パラグラフスタイルにlineHeightをセット
    NSMutableParagraphStyle *paragrahStyle = [[NSMutableParagraphStyle alloc] init];
    paragrahStyle.minimumLineHeight = height;
    paragrahStyle.maximumLineHeight = height;

    // NSAttributedStringを生成してパラグラフスタイルをセット
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:inText];
    [attributedText addAttribute:NSParagraphStyleAttributeName
                           value:paragrahStyle
                           range:NSMakeRange(0, attributedText.length)];
    label.attributedText = attributedText;
}

呼び出し方

ViewController.h に修正はありません。

ViewController.m


#import “ViewController.h”
//#import “common.h”
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label;
– (IBAction)labelButton:(id)sender;
@end

@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
?// Do any additional setup after loading the view, typically from a nib.
//NSString *tmp = [common escapeString:@”テスト&%$?”];
//NSLog(@”テスト&%%$? -> %@”,tmp);
_label.text = @”1?2?3″;
[common labelSpaceing:_labelMemberName height:20.0f inText:_label.text];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
– (IBAction)labelButton:(id)sender {
if ([_label.text isEqual: @”1?2?3″]) {
_label.text = @”1?2″;
} else {
_label.text = @”1?2?3″;
}
[common labelSpaceing:_labelMemberName height:20.0f inText:_label.text];
}
@end

実行結果

画像はありませんが、実行するとちょっと空間ができてるはずです。

このサイトのコードを利用させて戴きました。ほとんどまるまる使ってます(;´Д`)他のにも便利な使い方があるので詳しくはコチラをどうぞ

Qiita UILabelを使って行間や文字間を簡易的に調整する。

そのほかのObjective-C関連の記事をお探しならコチラをどうぞ

弊社から出している拙作スケジュールのアプリです。
是非ダウンロードして感想をお聞かせ下さい。

『Team Scheduler』 概要
▼アプリ価格: 無料
▼対応OS: iOS(iPhone/iPod Touch)、Android
▼カテゴリ: 仕事効率化(App Store)、ビジネス(Google Play)
▼対応言語: 日本語
▼推奨環境:
iOS版: iPhone4以降、iOS6. 0以降
Android版: Android OS 2. 3以降
▼ダウンロード:
App Storeからダウンロード
Google playで手に入れよう

この記事を書いた人

core-corp

入社年

出身地

業務内容

特技・趣味

テクログに関する記事一覧

TOP