无法计算iOS中文本区域的高度

时间:2014-03-26 16:25:31

标签: ios objective-c nsstring uitextview

我在我的应用程序中使用ios库UIPlaceHolderTextView:https://github.com/JohnnyZeng/UIPlaceHolderTextView链接到以下问题:

Placeholder in UITextView

库本身工作正常,但是,我需要在用户输入文本后计算区域的高度,不幸的是,尽管文本区域包含文本,但我总是得到0.00000的值。为什么是这样?这是我的相关代码:

//self.textView is a reference to a UIPlaceHolderTextView object, and text is its attribute

self.textView.text = @"Text that the user has entered, and can be of any length";
    float height = MIN(175, [self.textView.attributedText boundingRectWithSize:CGSizeMake(self.textView.frame.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:NULL].size.height);

NSLog(@"textview height is: %f", self.textView.frame.origin.y);
NSLog(@"textview height is: %f", self.textView.frame.size.height);

两行中的输出均为0.00000。谁能明白为什么会这样?我的猜测是问题在于self.textView.attributedText,但不确定我是否正确,如果是,我应该做什么。

2 个答案:

答案 0 :(得分:0)

您正在分配

`self.textView.text = @"Text that the user has entered, and can be of any length";`

并计算self.textView.attributedText的高度,我猜是否可以做适当的更改。它应该工作。

要使make工作,您应该为self.textView.attributedText

赋值

答案 1 :(得分:0)

Use a local textview of same width as real textview and set the same text with sizeToFit property.it will be returned in correct frame.

 UITextView *tv = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];

    //whatever alignment of real text view you have set
    tv.textAlignment = NSTextAlignmentJustified;
        tv.text= @"Text that the user has entered, and can be of any length";
    [tv sizeToFit];

    float height  =  tv.frame.size.height;