天天看点

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

}