2013-04-07 61 views
2

我想根據它將顯示的文本的數量來設置UITextView的高度。我發現這個解決這個放在這裏:無法從其內容設置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 

回答

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

+0

感謝您的快速回復,讓它立即與此工作! – user2255616 2013-04-07 22:28:55

+0

不客氣。如果答案對您有幫助,請考慮提升和/或接受它。 – 2013-04-07 22:29:33

+0

我已經接受,但不能upvote它,直到我有15名聲望:( – user2255616 2013-04-07 22:39:23

1

與其等待內容大小,您將在viewWillAppear中得到的,你爲什麼不試試這個:

  • 查找高度特定的文本需要使用- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode
  • 設置,爲的框架直接的textview。

而這是你可以在- (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... 
} 
相關問題