您的位置:首页 > 其它

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

2016-08-09 21:24 417 查看
    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

        

        //将光标
4000
设置回原来的位置

        demoTextView.selectedRange = NSRange(location: range.location + 1, length : 0)

        

        

    } 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: