2013年8月6日火曜日

UILabelの高さを計算する方法

UILabelの高さを計算する方法をメモで。

UILabelの高さを計算する

方法は以下のようになります。
// ラベルへ格納するテキスト(http://ja.wikipedia.org/wiki/Xbox_One より) (1)
NSString *comment = @"Xbox 360の次世代機種で、2013年5月21日に正式に発表された[4]。「全てのエンターテインメントをこの1台に集約させる」ことを意味するとされる[4]。映像出力は最大2160p(4K UHD 3840×2160)の解像度[5]、7.1chサラウンド対応。Xbox 360との後方互換はない。次世代の新型Kinectを同梱[6]。AMDのAPUやDDR3メモリとeSRAMを搭載。";

UILabel *commentLabel = [[UILabel alloc] init];

// 最大表示領域サイズ。文字列長がこのサイズを超える場合は"すべて"表示されない (2)
CGSize bounds = CGSizeMake(300, 10000);

// フォントを指定し、テキスト全体のサイズ取得 (3)
CGSize textSize = [comment sizeWithFont:[UIFont fontWithName:@"AppleGothic" size:13] constrainedToSize:bounds lineBreakMode:NSLineBreakByWordWrapping];

NSLog(@"textSize.w = %f, textSize.h = %f ", textSize.width, textSize.height);

commentLabel.frame = CGRectMake(10, 20, textSize.width, textSize.height);
commentLabel.textColor = [UIColor blackColor];
commentLabel.backgroundColor = [UIColor greenColor];
commentLabel.font = [UIFont fontWithName:@"AppleGothic" size:13];
commentLabel.textAlignment = NSTextAlignmentLeft;
[commentLabel setLineBreakMode:NSLineBreakByWordWrapping];
commentLabel.numberOfLines  = 0;
commentLabel.text = comment;

[self.view addSubview:commentLabel];

[commentLabel release];

ポイントとしては(1), (2), (3)のところで、あらかじめラベルへ入るテキストを取得し、そこからテキスト全体のサイズを取得しています。あとはframeプロパティを定義する際にその取得したサイズを入れています。

参考記事

文字列を描画したときの幅や高さを取得する - EZ-NET
【NSString】文字列から表示サイズを取得する方法 - iPhoneアプリ開発で稼げるのか
iPhoneでUILabelの高さ(height)を計算する方法 - 9ensanのLifeHack

0 件のコメント:

コメントを投稿