UIScrollView size to match UITextView size

2019-09-06 14:55发布

问题:

I have a UIScrollView with a block of text in a UITextView. The text could be any amount of words coming from a server.

I want the scroll view to be the correct scroll size to match the size of the UITextView.

What is the current practice to do this?

Screenshot:

回答1:

UITextView is an extension of UIScrollView. So you can get its content size using contentSize propery.



回答2:

You can use something like below to get the height for your textview

CGSize size = [@"Your string" 
           sizeWithFont:[UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:22] 
           constrainedToSize:CGSizeMake(500, CGFLOAT_MAX)];

_textView.frame = CGRectMake(x,y, width, size.height);  
_scrollview.frame = CGRectMake(x,y, width, size.height);  

or there is a littl hack you can use :p Use a Label to get the height for your text view.

   UILabel *tempLabel = [[UILabel alloc]initWithFrmae:_textView.bounds];
   tempLabel.numberOfLines = 0; // Important to do 
   tempLabel.text = @"Your Text";
   [tempLabel sizeToFit]; // This will resize your Label and now you can use it's height to manage your textView.

Now use this tempLabel's height

tempLabel.frame.size.height