Skip to content

Instantly share code, notes, and snippets.

@edom18
Created April 7, 2014 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edom18/10015091 to your computer and use it in GitHub Desktop.
Save edom18/10015091 to your computer and use it in GitHub Desktop.
[Objective-C] テキスト量に応じてTextViewを可変対応させる ref: http://qiita.com/edo_m18/items/a345a8d1d551e88d4013
aTextView.textContainer.lineFragmentPadding = 0;
aTextView.textContainerInset = UIEdgeInsetsZero;
UITextView *aTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 200, 0)];
aTextView.text = @"...some long text...";
// 200, 400のサイズ内に収まるサイズを取得
CGSize size = [aTextView.text sizeWithFont:self.textView.font
constrainedToSize:CGSizeMake(200, 400)];
CGRect frame = aTextView.frame;
frame.size.height = size.height;
aTextView.frame = frame;
CGSize checkSize = CGSizeMake(200, 400);
NSDictionary *attributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],
NSFontAttributeName:[UIFont systemFontOfSize:12.0]};
NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"some string"
attributes:attributes];
UITextView *aTextView = [[UITextView alloc] init];
aTextView.attributedText = string;
CGRect textFrame = [string boundingRectWithSize:checkSize
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
aTextView.frame = textFrame;
UITextView *aTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 200, 0)];
aTextView.text = @"some text.";
// 設定されたテキストのレンダリング結果を得るため、若干の遅延を挟む
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_MSEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
CGRect newFrame = aTextView.frame;
newFrame.size.height = aTextView.contentSize.height;
aTextView.frame = newFrame;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment