在寫自定義表情鍵盤的時候,一直在想如何才能做到像自帶鍵盤那樣可以隨心所欲的在任意位置添加和刪除表情圖標.大神們看到勿噴,小菜鳥只是想記錄下自己的遇到的一些問題. 測試環(huán)境 ?iOS7+
話不多說,那就直接上代碼了
1.在任意光標位置插入新表情
// 在string的任意位置插入新的表情
NSMutableAttributedString *stringAtr = [[NSMutableAttributedString alloc]initWithAttributedString:_textView.attributedText];
[stringAtr addAttribute:@"NSFontAttributeName"value:[UIFontsystemFontOfSize: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];
//獲取光標所在位置
NSIntegerlocation = [_textView offsetFromPosition:_textView.beginningOfDocumenttoPosition:_textView.selectedTextRange.start];
//將表情富文本插入光標所在位置
[stringAtr insertAttributedString:temp atIndex:location];
_textView.attributedText= stringAtr;
[selftextViewDidChange:_textView];
//改變光標的位置 ? 要在textViewDidChange 方法后調(diào)用才起作用
_textView.selectedRange= NSMakeRange(location + temp.length,0);
2.在任意光標位置刪除光標前的表情
NSIntegerlocation = [_textView offsetFromPosition:_textView.beginningOfDocumenttoPosition:_textView.selectedTextRange.start];
if(location <=0)
{
return;
}
NSMutableAttributedString * atr = [[NSMutableAttributedString alloc]initWithAttributedString:_textView.attributedText];
[atr deleteCharactersInRange:NSMakeRange(location-1,1)]; ? //刪除光標前一個字符
_textView.attributedText= atr;
[selftextViewDidChange:_textView];
_textView.selectedRange= NSMakeRange(location-1,0);