图文混排中,在textView的指定光标下插入文字或图片

    override func viewDidLoad() {

        super.viewDidLoad()
 
        demoTextView.text = "我是大帅比,真的是一个大帅比,确实是一个大帅比"

    }

    
    //插入文字
    @IBAction func insetText(sender: AnyObject) {
      
        //创建属性字符串
        let attrStr = NSAttributedString(string: "美女", attributes: [NSForegroundColorAttributeName:UIColor.redColor()])
        
        let font = demoTextView.font!
        
        //创建可变属性字符串
        let attrMutableStr = NSMutableAttributedString(attributedString: demoTextView.attributedText)
        
        //将图片属性字符串替换到可变属性字符串的某一个位置
        //获取光标所在位置
        let range = demoTextView.selectedRange
        
        //替换属性字符串
        attrMutableStr.replaceCharactersInRange(range, withAttributedString: attrStr)
        
        //显示属性字符串
        demoTextView.attributedText = attrMutableStr
        
        //将文字大小重置
        demoTextView.font = font
        
        //将光标设置回原来的位置
        demoTextView.selectedRange = NSRange(location: range.location + 2, length : 0)

    }


     //插入图片
    @IBAction func insetImage(sender: AnyObject) {
        
        //创建图片属性字符串
        let attachment = NSTextAttachment()
        attachment.image = UIImage(named: "5")
        let font = demoTextView.font!
        attachment.bounds = CGRectMake(0, -4, font.lineHeight, font.lineHeight)
        let attrImageStr = NSAttributedString(attachment: attachment)
        
        //创建可变属性字符串
        let attrMutableStr = NSMutableAttributedString(attributedString: demoTextView.attributedText)
        
        //将图片属性字符串替换到可变属性字符串的某一个位置
        //获取光标所在位置
        let range = demoTextView.selectedRange
        
        //替换属性字符串
        attrMutableStr.replaceCharactersInRange(range, withAttributedString: attrImageStr)
        
        //显示属性字符串
        demoTextView.attributedText = attrMutableStr
        
        //将文字大小重置
        demoTextView.font = font
        
        //将光标设置回原来的位置
        demoTextView.selectedRange = NSRange(location: range.location + 1, length : 0)
        
        
    } 

你可能感兴趣的:(杂)