uitextview根據內容算高度


 

UITextView根據內容自動改變frame

分類: iOS   190人閱讀  評論(0)  收藏  舉報

注意點:

textview中計算string占據的高度不能使用[NSStringsizeWithFont:constrainedToSize:],因為textView顯示文字有自己的樣式,在上下左右都有一定的偏移,所以先設置textView.text屬性,然后調用[UITextView sizeThatFits:(CGSize)size] 此函數返回的size就是在textviewtext顯示的區域大小。

 

[cpp]  view plain copy
 
  1. - (void)textViewDidChange:(UITextView *)textView  
  2. {  
  3.     [textView flashScrollIndicators];   // 閃動滾動條  
  4.       
  5.     static CGFloat maxHeight = 130.0f;  
  6.     CGRect frame = textView.frame;  
  7.     CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);  
  8.     CGSize size = [textView sizeThatFits:constraintSize];  
  9.     if (size.height >= maxHeight)  
  10.     {  
  11.         size.height = maxHeight;  
  12.         textView.scrollEnabled = YES;   // 允許滾動  
  13.     }  
  14.     else  
  15.     {  
  16.         textView.scrollEnabled = NO;    // 不允許滾動,當textview的大小足以容納它的text的時候,需要設置scrollEnabed為NO,否則會出現光標亂滾動的情況  
  17.     }  
  18.     textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);  
  19. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM