UIScrollView size to match UITextView size

2019-09-06 15:04发布

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:

enter image description here

2条回答
Summer. ? 凉城
2楼-- · 2019-09-06 15:31

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
查看更多
放荡不羁爱自由
3楼-- · 2019-09-06 15:40

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

查看更多
登录 后发表回答