@Gabe 给出的答案似乎直到 viewDidAppear 之后才在 iOS7.1 中起作用。请参阅下面的测试。
更新:实际上,情况更加复杂。如果您在 resizeTheTextView 方法中分配 textView.text,则在 iOS7 中,调整大小相当于只允许单行文本。严重奇怪。
UPDATE2:另请参阅iOS7 中不同的 UITextView 内容大小
UPDATE3:请参阅最底部的代码了解我现在正在使用的内容。似乎完成了这项工作。
#import "ViewController.h"
@interface ViewController ()
{
UITextView *textView;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 200, 1)];
[self.view addSubview:textView];
CALayer *layer = textView.layer;
layer.borderColor = [UIColor blackColor].CGColor;
layer.borderWidth = 1;
textView.text = @"hello world\n\n";
// Calling the method directly, after the view is rendered, i.e., after viewDidAppear, works on both iOS6.1 and iOS7.1
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:@"Change size" forState:UIControlStateNormal];
[button addTarget:self action:@selector(resizeTheTextView) forControlEvents:UIControlEventTouchUpInside];
[button sizeToFit];
CGRect frame = button.frame;
frame.origin.y = 400;
button.frame = frame;
[self.view addSubview:button];
// Works on iOS6.1, but does not work on iOS7.1
//[self resizeTheTextView];
}
- (void) viewWillAppear:(BOOL)animated
{
// Does not work on iOS7.1, but does work on iOS6.1
//[self resizeTheTextView];
}
- (void) viewDidAppear:(BOOL)animated
{
// Does work on iOS6.1 and iOS7.1
//[self resizeTheTextView];
}
- (void) resizeTheTextView
{
NSLog(@"textView.frame.size.height: %f", textView.frame.size.height);
NSLog(@"textView.contentSize.height: %f", textView.contentSize.height);
// 5) From https://stackoverflow.com/questions/728704/resizing-uitextview
CGRect frame = textView.frame;
UIEdgeInsets inset = textView.contentInset;
frame.size.height = textView.contentSize.height + inset.top + inset.bottom;
textView.frame = frame;
NSLog(@"inset.top: %f, inset.bottom: %f", inset.top, inset.bottom);
NSLog(@"textView.frame.size.height: %f", textView.frame.size.height);
NSLog(@"textView.contentSize.height: %f", textView.contentSize.height);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
更新3:
if ([[UIDevice currentDevice] majorVersionNumber] < 7.0) {
CGRect frame = _abstractTextView.frame;
UIEdgeInsets inset = _abstractTextView.contentInset;
frame.size.height = _abstractTextView.contentSize.height + inset.top + inset.bottom;
_abstractTextView.frame = frame;
}
else {
CGSize textViewSize = [_abstractTextView sizeThatFits:CGSizeMake(_abstractTextView.frame.size.width, FLT_MAX)];
_abstractTextView.frameHeight = textViewSize.height;
}