【问题标题】:Can't set UITextView height from its content无法从其内容设置 UITextView 高度
【发布时间】:2013-03-29 21:52:37
【问题描述】:

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

【问题讨论】:

    标签: ios xcode uitableview height


    【解决方案1】:

    您不能在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 视图的生命周期,您可能需要查看this very nice answer

    【讨论】:

    • 感谢您的快速回复,马上就可以使用了!
    • 不客气。如果答案对您有所帮助,请考虑投票和/或接受它。
    • 我已接受,但在获得 15 名声望之前无法投票 :(
    【解决方案2】:

    与其等待您将在 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...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-15
      • 2016-03-13
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      相关资源
      最近更新 更多