UITextView富文本、插入图片

直接看代码  

_textView  是定义的成员变量

 _textView = [[UITextView alloc]init];
    _textView.font = [UIFont systemFontOfSize:13];
    _textView.backgroundColor = [UIColor lightGrayColor];
    _textView.text = [NSString stringWithFormat:@"settttttttttt :%@",self.countStr];
    _textView.frame = CGRectMake(20, 100, 200, 130);
    _textView.delegate = self;
    [self.view addSubview:_textView];

通过代理方法  得到选中文字的起始位置和长度  通过定义成员变量的方式保存起来  代码如下

- (void)textViewDidChangeSelection:(UITextView *)textView {
    
    /**
     * 可以通过得到复制的长度进行判断是否有进行复制操作  再通过位置、长度进行字体变化
     */
    _loc = (int)textView.selectedRange.location;
    _len = (int)textView.selectedRange.length;
    
}

富文本   让选中的字体加粗或者改变颜色都可以  代码中是点击按钮触发字体选中改变方法

- (void)btnClick{
    
    if (_len) {  
        
        //怎么让选中的字体加粗呢
        NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:_textView.text];
        [AttributedStr addAttribute:NSFontAttributeName
         
                              value:[UIFont boldSystemFontOfSize:15.0]
         
                              range:NSMakeRange(_loc, _len)];
        
        _textView.attributedText = AttributedStr;
        
        
        
    }
    
}

图片插入  代码中也是通过按钮触发方法  点击按钮 复制一张图片到光标位置

- (void)copyBtnClick{
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithAttributedString:_textView.attributedText];
    
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil] ;
    textAttachment.image = [UIImage imageNamed:@"111"]; //要添加的图片
    
    NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment] ;
    
    [string insertAttributedString:textAttachmentString atIndex:_textView.selectedRange.location];//index为用户指定要插入图片的位置
    _textView.attributedText = string;

}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值