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

  • 相关阅读:
    Django 之Ajax&Json&CORS&同源策略&Jsonp用法
    Django 基于Ajax & form 简单实现文件上传
    自定义分页
    【学员管理系统】0x04 数据库连接优化
    【学员管理系统】0x03 老师信息管理功能
    【学员管理系统】0x02 学生信息管理功能
    【学员管理系统】0x01 班级信息管理功能
    webpack那些事儿
    前端发展趋势
    好人不一定能做一个优秀的管理者
  • 原文地址:https://www.cnblogs.com/designyshy/p/5733218.html
Copyright © 2011-2022 走看看