iOS 實現(xiàn)在string任意位置添加新的表情

在寫自定義表情鍵盤的時候,一直在想如何才能做到像自帶鍵盤那樣可以隨心所欲的在任意位置添加和刪除表情圖標.大神們看到勿噴,小菜鳥只是想記錄下自己的遇到的一些問題. 測試環(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);

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容