我們一定使用過通訊App,輸入框會隨著字數多換行而高度變大。四年前我寫過文章:動態框架 (Dynamic Frame),這次我要來講進階用法,就是邊打字邊算輸入框的高度:TextView 動態高度 (TextView Dynamic Height)。
如上圖,我要打三元合一的緣由,從第一行開始,到「兩千年」的下一個字,就會計算兩行高度,此時需要實作TextView的Delegate,每打一字就會觸發:
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
就在裡頭就能即時運算高度。
想要讓使用者體驗變好,就這麼做吧~
/**
Theme: TextView Dynamic Height
IDE: Xcode 10
Language: Objective C
Date: 108/05/23
Author: HappyMan
Blog: https://cg2010studio.com/
*/
#pragma mark - UITextViewDelegate
-(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]];
}
return YES;
}
- (float)heightForTextView:(UITextView *)textView WithText:(NSString *)strText
{
CGSize constraint = CGSizeMake(textView.contentSize.width - kTitleTextViewFixedPadding, CGFLOAT_MAX);
CGRect size = [strText boundingRectWithSize:constraint
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:@{NSFontAttributeName:textView.font}
context:nil];
float textHeight = size.size.height + kTitleTextViewFixedPadding;
return textHeight;
}
以上有處理三種輸入狀況:
- 打字
- 空字串
- 消字
我後來發現算得不夠精準,於是我提供了kTitleTextViewFixedPadding來調整,盡可能做到盡善盡美:)~

Comments on: "[iOS] TextView 動態高度 (TextView Dynamic Height)" (3)
這個臉變形也太好笑XD, 你貼code是用wordpress插件嗎? 插件wordpress都說要升級商業版才能裝囧
讚Liked by 1 person
那是返老還童濾鏡做的唷~
我是用語法囉~
可以參考文章:[WordPress] 在WordPress上放程式碼
讚Liked by 1 person
讚啦~成功了, 簡單易用的好招
讚Liked by 1 person