IOS图文混排(swift)

2016-08-03  本文已影响0人  lg大大
let attachment = NSTextAttachment()
attachment.image = UIImage(contentsOfFile: emoticon.pngPath!)
let font = textView.font!
attachment.bounds = CGRect(x: 0, y: 0, width: font.lineHeight, height: font.lineHeight)
 let attrImageStr = NSAttributedString(attachment: attachment)
let attrMStr = NSMutableAttributedString(attributedString: textView.attributedText)
        // 1.获取光标所在的位置
let range = textView.selectedRange
        
        // 2.替换属性字符串
attrMStr.replaceCharactersInRange(range, withAttributedString: attrImageStr)
        
        // 显示属性字符串
textView.attributedText = attrMStr
        
        // 将文字的大小重置
textView.font = font
        
        // 将光标设置回原来位置 + 1
textView.selectedRange = NSRange(location: range.location + 1, length: 0)
上一篇下一篇

猜你喜欢

热点阅读