IOS图文混排(swift)

    1. 创建属性字符
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)
  • 2.创建可变属性字符串
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)

你可能感兴趣的:(IOS图文混排(swift))