我正在尝试根据它将显示的文本量来设置UITextView的高度。我在这里找到了这个解决方案:
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;
但我无法让它工作,我认为这与我没有正确使用addSubview将UITextView添加到视图有关,但我无法弄明白!我相信这很容易解决。
这是我的viewcontroller.m文件代码
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize textView = _textView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view addSubview: _textView];
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
答案 0 :(得分:3)
由于尚未设置textView框架,因此无法在viewDidLoad
中执行此操作。
使用更合适的方法移动代码,例如viewWillAppear:
或viewDidLayoutSubviews
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;
}
如果您想更好地了解UIViewController
视图的生命周期,可能需要查看this very nice answer。
答案 1 :(得分:1)
不要等待ViewWillAppear中的内容大小,为什么不试试这个:
-
(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
lineBreakMode:(NSLineBreakMode)lineBreakMode
这是您可以在- (void)viewDidLoad
方法本身中实现的。
- (void)viewDidLoad {
NSString *aMessage = @""; // Text
UIFont *aFont = [UIFont systemFontOfSize:20]; // Font required for the TextView
CGFloat aTextViewWidth = 180.00; // Widht of the TextView
CGSize aSize = [aMessage sizeWithFont:aFont constrainedToSize:CGSizeMake(aTextViewWidth, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
CGFloat aTextViewHeight = aSize.height;
UITextView *aTextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, aTextViewWidth, aTextViewHeight)];
// Rest of your Code...
}