iOS:如何優雅的讓UITextView根據輸入文字實時改變高度

iOS:如何優雅的讓UITextView根據輸入文字實時改變高度

UITextView的高度隨着輸入文字實時的改變是app中非常常見的功能,社交軟件的文字輸入框、評論框都會用到
網上有很多UITextView的高度隨着輸入文字實時改變的demo,筆者看了很多,很多雖然可以實現相應的功能但是有些細節實現的不是很好,所以筆者在參考前人的基礎上,做了些許優化,希望能對讀者有所幫助

一言不合貼代碼:

  • 創建UITextView 
      // 下面這一段代碼,筆者就不費口舌了,讀者應該都看的懂,就是創建一個外觀類似於UITextField的UITextView
      self.contentTextView = [[UITextView alloc]initWithFrame:CGRectMake((kMainBoundsWidth-250)/2, kMainBoundsHeight/2-50, 250, 39)];
      self.contentTextView .layer.cornerRadius = 4;
      self.contentTextView .layer.masksToBounds = YES;
      self.contentTextView .delegate = self;
      self.contentTextView .layer.borderWidth = 1;
      self.contentTextView .font = [UIFont systemFontOfSize:14];
      self.contentTextView .layer.borderColor = [[[UIColor lightGrayColor] colorWithAlphaComponent:0.4] CGColor];
      //加下面一句話的目的是,是爲了調整光標的位置,讓光標出現在UITextView的正中間
      self.contentTextView.textContainerInset = UIEdgeInsetsMake(10,0, 0, 0);
      [self.view addSubview:self.contentTextView ];
  • 實現的關鍵:UITextView 的一個代理方法- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
    這個代理方法可能很多新手都不太常用,UITextView 每此輸入字符都會走該方法,在這個方法中實時計算輸入文字的高度,從而動態調整UITextView 的高度是最合適不過的。

1.計算輸入文字高度的方法,之所以返回的高度值加22是因爲UITextView有一個初始的高度值40,但是輸入第一行文字的時候文字高度只有18,所以UITextView的高度會發生變化,效果不太好

  - (float) heightForTextView: (UITextView *)textView WithText: (NSString *) strText{
    CGSize constraint = CGSizeMake(textView.contentSize.width , CGFLOAT_MAX);
    CGRect size = [strText boundingRectWithSize:constraint
                                             options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                          attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]}
                                             context:nil];
    float textHeight = size.size.height + 22.0;
    return textHeight;
}

2.在- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;中一步步實現我們的效果:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    CGRect frame = textView.frame;
    float  height = [ self heightForTextView:textView WithText:textView.text];
    frame.size.height = height;
    [UIView animateWithDuration:0.5 animations:^{

            textView.frame = frame;

        } completion:nil];

    return YES;
}

如上面一段代碼,我們在輸入文字的時候實時計算textView中的文字,就可以得到我們想要的高度,效果如何呢?


UITextView01


細心的讀者可能發現了,在第二行輸入第一個字的時候,frame沒有更改,輸入第二個字的時候才發生更改,第三行同樣如此,什麼原因呢?

筆者打斷點調試後,終於找到問題的根源,回過頭來再看- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;這個方法,可以看到該方法有兩個參數textView 和text,在方法我們計算的是textView.text的高度,但實際上這裏存在一個問題,每次輸入文字後調用該方法,此時輸入的文字並不在textView.text中,而在另一個參數text中,走完該方法後每次輸入的文字才加入到textView.text中。筆者選擇的解決方案是將textView.text和text文字拼接起來

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    CGRect frame = textView.frame;
    float height = [self heightForTextView:textView WithText:[NSString stringWithFormat:@"%@%@",textView.text,text]];
    frame.size.height = height;
    [UIView animateWithDuration:0.5 animations:^{

            textView.frame = frame;

        } completion:nil];

    return YES;
}

再來看下效果:


UITextView02


可以看出,現在滿足了我們剛纔的要求,在第二行第一次輸入的時候,可以更改frame了,但是新的問題又出現了,就是刪除字符的時候,當第二行被刪光的時候,沒有直接計算frame,直到刪除第一行某個文字的時候纔會計算,這是爲什麼呢?
筆者調試過後,發現按刪除鍵的時候,text的文字爲@"",每次按刪除鍵,調用該方法的時候,textView.text此時並沒有把該字符刪掉,所以計算的還是第一行加第二行文字的高度,因此我們可以根據text的內容做條件判斷,如果text內容爲@"",我們通過截取字符串的方式手動去掉一個字符

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    CGRect frame = textView.frame;
    float height;
    if ([text isEqual:@""]) {
     height = [ self heightForTextView:textView WithText:[textView.text substringToIndex:[textView.text length] - 1]];
    }else{
     height = [self heightForTextView:textView WithText:[NSString stringWithFormat:@"%@%@",textView.text,text]];
     }

    frame.size.height = height;
    [UIView animateWithDuration:0.5 animations:^{

            textView.frame = frame;

        } completion:nil];

    return YES;
}

效果圖:


UITextView03

基本上實現了需求,有一個小bug,造成了閃退,textView.text爲空的時候,截取字符串會越界造成閃退,加一個條件判斷就好了

終極代碼:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    CGRect frame = textView.frame;
    float height;
    if ([text isEqual:@""]) {

        if (![textView.text isEqualToString:@""]) {

            height = [ self heightForTextView:textView WithText:[textView.text substringToIndex:[textView.text length] - 1]];

        }else{

            height = [ self heightForTextView:textView WithText:textView.text];
        }
    }else{

            height = [self heightForTextView:textView WithText:[NSString stringWithFormat:@"%@%@",textView.text,text]];
    }

    frame.size.height = height;
    [UIView animateWithDuration:0.5 animations:^{

            textView.frame = frame;

        } completion:nil];

    return YES;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章