zoukankan      html  css  js  c++  java
  • iOS 实现在string任意位置添加新的表情

    在写自定义表情键盘的时候,一直在想如何才能做到像自带键盘那样可以随心所欲的在任意位置添加和删除表情图标.大神们看到勿喷,小菜鸟只是想记录下自己的遇到的一些问题. 测试环境 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);

  • 相关阅读:
    UVa 1592 Database(巧用map)
    TZOJ 4746 Xiangqi(模拟棋盘数组)
    TZOJ 1545 Hurdles of 110m(01背包dp)
    TZOJ 2754 Watering Hole(最小生成树Kruskal)
    TZOJ 1242 求出前m大的数(预处理)
    TZOJ 5280 搜索引擎(模拟字符串)
    TZOJ 4865 统计单词数(模拟字符串)
    TZOJ 5279 马拉松比赛(广搜)
    [luogu4735]最大异或和
    小奇回地球
  • 原文地址:https://www.cnblogs.com/designyshy/p/5733218.html
Copyright © 2011-2022 走看看