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);

  • 相关阅读:
    winform 单选框, 图像控件,图像列表,状态栏,定时器,绘图
    学习资料链接,csdn博客
    c# 基本控件,窗口程序
    Gmap.net 怎么导入离线地图
    修改MFC主窗口界面标题和图标的方法
    vc6.0缓冲区
    vc6.0编译出错,删除多余的文件,清空重新编译
    Tomcat插件与Jetty插件在MyEclipse中的配置
    div里面的内容超出自身高度时,显示省略号
    aptana studio 3 自动换行(无需插件)
  • 原文地址:https://www.cnblogs.com/designyshy/p/5733218.html
Copyright © 2011-2022 走看看