How to adjust the height of a textview to his content in SWIFT?

前端 未结 7 761
无人及你
无人及你 2020-12-07 23:05

In my view controller, I have an UITextView. This textview is filled with a string. The string can be short or long. Depending on the length of the string, the height of the

7条回答
  •  心在旅途
    2020-12-07 23:46

    First, disable UITextView's scrollable. Two options:

    1. uncheck Scrolling Enabled in .xib.
    2. [TextView setScrollEnabled:NO];

    Create a UITextView and connect it with IBOutlet (TextView). Add a UITextView height constraint with default height, connect it with IBOutlet (TextViewHeightConstraint). When you set your UITextView’s text asynchronously you should calculate the height of UITextView and set UITextView’s height constraint to it. Sample code:

    CGSize sizeThatFitsTextView = [TextView sizeThatFits:CGSizeMake(TextView.frame.size.width, MAXFLOAT)];
    
    TextViewHeightConstraint.constant = sizeThatFitsTextView.height; 
    

提交回复
热议问题