Skip to content

Instantly share code, notes, and snippets.

@TachibanaKaoru
Last active December 25, 2015 20:38
Show Gist options
  • Save TachibanaKaoru/7036140 to your computer and use it in GitHub Desktop.
Save TachibanaKaoru/7036140 to your computer and use it in GitHub Desktop.
UILabelとUITextViewのsizeWithFont:constrainedToSizeを使って表示テキストによってサイズを変更します。 (http://www.toyship.org/archives/1437)
- (void)viewDidLoad
{
[super viewDidLoad];
// UILabelの場合
UILabel* myLabel = [[UILabel alloc] init];
myLabel.text = @"Every great iOS app starts with a great idea, but translating that idea into actions requires some planning. Every iOS app relies heavily on design patterns, and those design patterns influence much of the code you need to write. So before you write any code, take the time to explore the possible techniques and technologies available for writing that code. Doing so can save you a lot of time and frustration.";
myLabel.font = [UIFont systemFontOfSize:12.0];
myLabel.backgroundColor = [UIColor blueColor];
myLabel.numberOfLines = 0; //これがないとUILabelが複数行になりません。
CGRect frame1 = CGRectMake(0,100,200,100);
// 幅200,高さ900のRectの中に表示したときのサイズを計算
CGSize size1 = [myLabel.text sizeWithFont:myLabel.font
constrainedToSize:CGSizeMake(200, 900)];
frame1.size.height = size1.height;
myLabel.frame = frame1;
[self.view addSubview:myLabel];
// UITextViewの場合
UITextView* myTextView = [[UITextView alloc] init];
myTextView.text = @"Every great iOS app starts with a great idea, but translating that idea into actions requires some planning. Every iOS app relies heavily on design patterns, and those design patterns influence much of the code you need to write. So before you write any code, take the time to explore the possible techniques and technologies available for writing that code. Doing so can save you a lot of time and frustration.";
myTextView.font = [UIFont systemFontOfSize:12.0];
myTextView.backgroundColor = [UIColor redColor];
myTextView.editable = NO;
CGRect frame2 = CGRectMake(0,300,200,100);
// 幅180,高さ900のRectの中に表示したときのサイズを計算
CGSize size2 = [myTextView.text sizeWithFont:myTextView.font
constrainedToSize:CGSizeMake(180, 900)];
frame2.size.height = size2.height;
myTextView.frame = frame2;
[self.view addSubview:myTextView];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment