简体   繁体   中英

How to get UITextView height according to content in iOS 9

I'm using a UITextView to display some data. I need to calculate the height of the UITextView depending on its content. I have tried contentSize.height , but it doesn't work for me. Does anyone have a solution for this? Here is my code with 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.scrollEnabled = false

this will make the textView aware of its content and it will grow or shrink in height based on its content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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