天天看點

UITextView富文本輸入并自适應高度(解決中文輸入法候選詞bug)

-(void)textViewDidChange:(UITextView *)textView{

// markedTextRange不等于空時表示有候選字元,在中文輸入情況下,有候選字元時會導緻在進行富文本替換時加入候選字元

if (textView.markedTextRange == nil) {

//記錄光标位置

NSRange rang = textView.selectedRange;

[self exchangeAttributedText:textView.text]; //替換富文本後将光标移動到記錄位置

textView.selectedRange = rang;

[self autoHeightTextViewtext:textView.text];

}

}

//自動計算文字高度

-(void)autoHeightTextViewtext:(NSString*)textStr{

UITextView*newText = [[UITextView alloc]initWithFrame:self.textContent.frame];

newText.textContainerInset = UIEdgeInsetsZero;

newText.attributedText = self.textContent.attributedText;

CGSize heightSize = [newText sizeThatFits:CGSizeMake(newText.width ,MAXFLOAT ) ];

self.csText.constant = heightSize.height>80?heightSize.height +20 : 80 + 20;

}

//替換富文本

-(void)exchangeAttributedText:(NSString*)textStr{

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

paragraphStyle.lineSpacing = 5;// 字型的行間距

NSDictionary*attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:16],NSParagraphStyleAttributeName:paragraphStyle};

self.textContent.attributedText = [[NSAttributedString alloc] initWithString:textStr attributes:attributes];

}