1. 程式人生 > >UITextView高度隨文字自動增加類似於微信

UITextView高度隨文字自動增加類似於微信

專案要求 1、UITextView的高度隨文字的增加而增加,類似微信 2、多於3行不再增加UITextView的高度 3、是親測78高度三行,根據文字大小的不同親們自行定義,靈活運用 查了很多網站都是在 - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ }  - (void)textViewDidChange:(UITextView *)textView{ } 中作處理,我試了一下,多多少少都有些問題,不是很完美,因此改變策略
使用通知: [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(textViewTextDidChange:) name:UITextViewTextDidChangeNotificationobject:self.textView]; 總算問題少了很多,親測目前使用還行,歡迎大家發現問題留言 原始碼: @interfaceTextViewHeightController ()<UITextViewDelegate> @property(nonatomic,strong) UITextView
*textView; //是否有滾動 @property (nonatomic, assign, getter=scrollFlag) BOOL flag; @end - (void)viewDidLoad {     [superviewDidLoad]; self.navBar.titleLabel.text = @"UITextView高度隨文字自動增加"; //UITextView self.textView = [[UITextViewalloc]initWithFrame:CGRectMake(100, 64 + 150, SCREEN_WIDTH - 200, 30)]; self.textView
.font = [UIFontsystemFontOfSize:17.0f]; self.textView.delegate = self; self.textView.layer.masksToBounds = YES; self.textView.layer.borderWidth = 0.5; self.textView.layer.borderColor = [UIColorlightGrayColor].CGColor; //調整游標的位置,讓光標出現在UITextView的正中間 self.textView.textContainerInset = UIEdgeInsetsMake(5,0, 0, 0);     [self.viewaddSubview:self.textView]; //改變文字的通知     [[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(textViewTextDidChange:) name:UITextViewTextDidChangeNotificationobject:self.textView]; // Do any additional setup after loading the view. } //通知 -(void)textViewTextDidChange:(NSNotification *)notification{ //空格使用@" "來代替 if([_textView.texthasPrefix:@""]){ _textView.text=[_textView.textstringByReplacingOccurrencesOfString:@" "withString:@""];     } CGFloat height = _textView.contentSize.height>78?78:_textView.contentSize.height+5;     [UIViewanimateWithDuration:0.3animations:^{ _textView.frame=CGRectMake(100, CGRectGetMaxY(_textView.frame)-height, _textView.frame.size.width, height);     }]; return; } //可以滾動 - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{ _flag=YES; } //不可以滾動 - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{ _flag=NO; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView{ /**      *  判斷是否拖動來設定frame      */ if(!self.scrollFlag){ NSLog(@"%lf",_textView.contentSize.height); if(_textView.contentSize.height>78){             [_textViewsetContentOffset:CGPointMake(0, _textView.contentSize.height-78 + 5)];         }else{           [_textViewsetContentOffset:CGPointMake(0, 0)];         }     } } OK !!!!!!!!!!!