iOS:如何優(yōu)雅的讓UITextView根據(jù)輸入文字實(shí)時改變高度

demo
前言:

UITextView的高度隨著輸入文字實(shí)時的改變是app中非常常見的功能,社交軟件的文字輸入框、評論框都會用到
網(wǎng)上有很多UITextView的高度隨著輸入文字實(shí)時改變的demo,筆者看了很多,很多雖然可以實(shí)現(xiàn)相應(yīng)的功能但是有些細(xì)節(jié)實(shí)現(xiàn)的不是很好,所以筆者在參考前人的基礎(chǔ)上,做了些許優(yōu)化,希望能對讀者有所幫助

一言不合貼代碼:

  • 創(chuàng)建UITextView
    // 下面這一段代碼,筆者就不費(fèi)口舌了,讀者應(yīng)該都看的懂,就是創(chuàng)建一個外觀類似于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];
    //加下面一句話的目的是,是為了調(diào)整光標(biāo)的位置,讓光標(biāo)出現(xiàn)在UITextView的正中間
    self.contentTextView.textContainerInset = UIEdgeInsetsMake(10,0, 0, 0);
    [self.view addSubview:self.contentTextView ];
  • 實(shí)現(xiàn)的關(guān)鍵:UITextView 的一個代理方法- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
    這個代理方法可能很多新手都不太常用,UITextView 每此輸入字符都會走該方法,在這個方法中實(shí)時計(jì)算輸入文字的高度,從而動態(tài)調(diào)整UITextView 的高度是最合適不過的。

1.計(jì)算輸入文字高度的方法,之所以返回的高度值加22是因?yàn)閁ITextView有一個初始的高度值40,但是輸入第一行文字的時候文字高度只有18,所以UITextView的高度會發(fā)生變化,效果不太好

  - (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;中一步步實(shí)現(xiàn)我們的效果:

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

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


UITextView01

細(xì)心的讀者可能發(fā)現(xiàn)了,在第二行輸入第一個字的時候,frame沒有更改,輸入第二個字的時候才發(fā)生更改,第三行同樣如此,什么原因呢?

筆者打斷點(diǎn)調(diào)試后,終于找到問題的根源,回過頭來再看- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;這個方法,可以看到該方法有兩個參數(shù)textView 和text,在方法我們計(jì)算的是textView.text的高度,但實(shí)際上這里存在一個問題,每次輸入文字后調(diào)用該方法,此時輸入的文字并不在textView.text中,而在另一個參數(shù)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

可以看出,現(xiàn)在滿足了我們剛才的要求,在第二行第一次輸入的時候,可以更改frame了,但是新的問題又出現(xiàn)了,就是刪除字符的時候,當(dāng)?shù)诙斜粍h光的時候,沒有直接計(jì)算frame,直到刪除第一行某個文字的時候才會計(jì)算,這是為什么呢?
筆者調(diào)試過后,發(fā)現(xiàn)按刪除鍵的時候,text的文字為@"",每次按刪除鍵,調(diào)用該方法的時候,textView.text此時并沒有把該字符刪掉,所以計(jì)算的還是第一行加第二行文字的高度,因此我們可以根據(jù)text的內(nèi)容做條件判斷,如果text內(nèi)容為@"",我們通過截取字符串的方式手動去掉一個字符

- (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

基本上實(shí)現(xiàn)了需求,有一個小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;
}

** 結(jié)語:**

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容