2

我正在尝试根据它将显示的文本量设置 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
4

2 回答 2

3

viewDidLoad由于尚未设置 textView 框架,因此您无法执行此操作。

以更合适的方法移动您的代码,例如viewWillAppear:viewDidLayoutSubviews

- (void)viewWillAppear:(BOOL)animated {
   [super viewWillAppear:animated];

   CGRect frame = _textView.frame;
   frame.size.height = _textView.contentSize.height;
   _textView.frame = frame;
}

如果您想更好地了解UIViewController视图的生命周期,您可能需要查看这个非常好的答案

于 2013-04-07T22:25:13.440 回答
1

Instead of waiting for the Content Size, which you will get in ViewWillAppear, why dont you try this:

  • Find the height a particular text will need using - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode
  • Set that to the frame of the textview directly.

And this is something that you can achieve in the - (void)viewDidLoad method itself.

- (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...
}
于 2013-04-07T22:36:37.050 回答