简体   繁体   English

如何根据iOS 9中的内容获取UITextView高度

[英]How to get UITextView height according to content in iOS 9

I'm using a UITextView to display some data. 我正在使用UITextView显示一些数据。 I need to calculate the height of the UITextView depending on its content. 我需要根据其内容计算UITextView的高度。 I have tried contentSize.height , but it doesn't work for me. 我已经尝试过contentSize.height ,但是对我来说不起作用。 Does anyone have a solution for this? 有人对此有解决方案吗? Here is my code with AutoLayout. 这是我使用AutoLayout的代码。 I have set the height constraint with outlet 我已经设置了出口的高度限制

CGFloat height= _myTextView.contentSize.height;
_heightConstraint.constant = height;

First size the text view to the content with: 首先使用以下内容将文本视图调整为内容大小:

[yourtTextView sizetofit];

Then get the height of the view with: 然后使用以下方法获取视图的高度:

double textViewHeight = yourtTextView .frame.size.height;

You could use the following to work out the height of the text, works perfectly for me: 您可以使用以下方法计算出文字的高度,非常适合我:

CGSize maximumTextViewSize = CGSizeMake(textView.frame.size.width, CGFLOAT_MAX);

NSStringDrawingOptions options = NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin;
NSDictionary *attr = @{NSFontAttributeName: [your font and font size]};

CGRect textViewBounds = [theText boundingRectWithSize:maximumTextViewSize
                                              options:options
                                           attributes:attr
                                              context:nil];

CGFloat height = ceilf(textViewBounds.size.height);

Just add 只需添加

[self layoutIfNeeded]

After you've calculated the height, and you should be alright. 计算高度后,您应该没事。

If not, come back to me. 如果没有,请回到我身边。

func heightForView(text:String, font:UIFont, width:CGFloat, xpos:CGFloat) -> CGFloat {
        let label:UILabel = UILabel(frame: CGRectMake(xpos, 0, width, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        label.font = font
        label.text = text

        label.sizeToFit()
        return label.frame.height
    }

The textView is not aware of its content when the text view scroll is enabeld change that in the storyboard by unchecking the Scrolling enables or by code by adding this: 启用文本视图滚动时,通过取消选中“滚动启用”或通过添加以下代码,可更改故事板中的内容,textView不会意识到其内容:

textview.scrollEnabled = false

this will make the textView aware of its content and it will grow or shrink in height based on its content. 这将使textView知道其内容,并且其高度将根据其内容而增加或缩小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM