在写自定义表情键盘的时候,一直在想如何才能做到像自带键盘那样可以随心所欲的在任意位置添加和删除表情图标.大神们看到勿喷,小菜鸟只是想记录下自己的遇到的一些问题. 测试环境 iOS7+ 话不多说,那就直接上代码了
1.在任意光标位置插入新表情
// 在string的任意位置插入新的表情
NSMutableAttributedString *stringAtr = [[NSMutableAttributedString alloc]initWithAttributedString:_textView.attributedText];
[stringAtr addAttribute:@"NSFontAttributeName" value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, stringAtr.length)];
NSTextAttachment * atttachment = [[NSTextAttachment alloc]init];
atttachment.image = image;
// 设置富文本图片的位置大小
atttachment.bounds = CGRectMake(0, -4, 16, 16);
NSAttributedString *temp = [NSAttributedString attributedStringWithAttachment:atttachment];
//获取光标所在位置
NSInteger location = [_textView offsetFromPosition:_textView.beginningOfDocument toPosition:_textView.selectedTextRange.start];
//将表情富文本插入光标所在位置
[stringAtr insertAttributedString:temp atIndex:location];
_textView.attributedText = stringAtr;
[self textViewDidChange:_textView];
//改变光标的位置 要在textViewDidChange 方法后调用才起作用
_textView.selectedRange = NSMakeRange(location + temp.length , 0);
2.在任意光标位置删除光标前的表情
NSInteger location = [_textView offsetFromPosition:_textView.beginningOfDocument toPosition:_textView.selectedTextRange.start];
if(location <= 0)
{
return ;
}
NSMutableAttributedString * atr = [[NSMutableAttributedString alloc]initWithAttributedString:_textView.attributedText];
[atr deleteCharactersInRange:NSMakeRange(location-1, 1)];
_textView.attributedText = atr;
[self textViewDidChange:weakSelf->_textView];
_textView.selectedRange = NSMakeRange(location-1,0);