1. 程式人生 > >iOS:如何優雅的讓UITextView根據輸入文字實時改變高度

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

demo
前言:

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;
}

結語:

筆者只是實現了簡單的需求,可能很多地方還不夠完善,也可能存在bug,歡迎批評,指正,共同交流。



文/Flying_Einstein(簡書作者)
原文連結:http://www.jianshu.com/p/9e960757de86
著作權歸作者所有,轉載請聯絡作者獲得授權,並標註“簡書作者”。