currentLineNum = 1;//默認文本框顯示一行文字
NSDictionary *dict=@{NSFontAttributeName:[UIFont systemFontOfSize:14.0]};
CGSize contentSize=[@"我" sizeWithAttributes:dict];
heightText = contentSize.height;
self.textView.font = [UIFont systemFontOfSize:14.0];
self.textView.textContainerInset = UIEdgeInsetsZero;
self.textView.textContainer.lineFragmentPadding = 0;
self.textView.delegate = self;
#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
float textViewWidth = self.textView.frame.size.width;//取得文本框高度
NSString *content = textView.text;
NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:14.0]};
CGSize contentSize = [content sizeWithAttributes:dict];//計算文字長度
float numLine = ceilf(contentSize.width/textViewWidth);
if(numLine > currentLineNum ){
//如果發現當前文字長度對應的行數超過。 文本框高度,則先調整當前view的高度和位置,然後調整輸入框的高度,最後修改currentLineNum的值
self.layoutViewTextHeight.constant = self.textView.frame.size.height+heightText*(numLine-currentLineNum) + 28.0;
currentLineNum = numLine;
}else if (numLine < currentLineNum ){
//次數爲刪除的時候檢測文字行數減少的時候
if (numLine <= 1) {
self.layoutViewTextHeight.constant = 48.0;
}else {
self.layoutViewTextHeight.constant = self.textView.frame.size.height-heightText*(currentLineNum-numLine) + 28.0;
}
}
if (numLine == 0) {
numLine = 1;
}
currentLineNum = numLine;
}
- (void)scrollViewDidScroll:(UIScrollView*)scrollView {
// 防止換行時抖動
scrollView.contentOffset = CGPointZero;
}
UITextView自適應高度
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.