使用场景,使用UITextview输入中文,切输入框能够根据输入内容进行动态的高度改变,(或者输入框的内容需要设置行间距和字间距)
问题复现图片
问题原因:是因为当我们正在输入拼音时就会调用textViewDidChange代理方法,所以为题也就出现在这里
解决方案:
第一步:对textViewDidChange进行数据筛选,当我们输入的是空格开头或者回车结尾或者是三个连续空格时才进行我们需要的一系列操作,其余不操作
第二步:解决通过键盘输入导致输入框高度无法改变问题,通过获取newText(如下),判断newText的length是否为0.到此方案确定,问题解决.
UITextRange *selectedRange = [textView markedTextRange];
NSString *newText = [textView textInRange:selectedRange];
附上代理方法
- (void)textViewDidChange:(UITextView *)theTextView
{
Bool _change = NO;
UITextRange *selectedRange = [theTextView markedTextRange];
NSString *newText = [theTextView textInRange:selectedRange];
if (newText.length == 0) {
_change = YES;
}
//不输入换行
if ([theTextView.text hasSuffix:@"\n"])
{
NSMutableString * textViewStr = [NSMutableString stringWithString:theTextView.text];
[textViewStr deleteCharactersInRange:NSMakeRange(textViewStr.length-1,1)];
theTextView.text = textViewStr;
_change = YES;
}
//不以空格开头
if ([theTextView.text hasPrefix:@" "])
{
NSMutableString * textViewStr = [NSMutableString stringWithString:theTextView.text ];
[textViewStr deleteCharactersInRange:NSMakeRange(0,1)];
theTextView.text = textViewStr;
_change = YES;
}
//不以三个空格结尾
if ([theTextView.text hasSuffix:@" "])
{
NSMutableString * textViewStr = [NSMutableString stringWithString:theTextView.text];
[textViewStr deleteCharactersInRange:NSMakeRange(textViewStr.length-2,1)];
theTextView.text = textViewStr;
_change = YES;
}
NSLog(@"===实时=%@",theTextView.text);
if (_change){
//下面的功能根据自己的需要进行正常操作,附上示例代码
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 10.5;// 字体的行间距
NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:13],
NSParagraphStyleAttributeName:paragraphStyle,
NSKernAttributeName:@0.5f
};
self.textView.attributedText = [[NSAttributedString alloc] initWithString:self.textView.text attributes:attributes];
}
}
最后效果图片
ps:如有不足还望告知,谢谢