TextView

退格

textView.deleteBackward()

在光标位置插入

let textRenge = textView.selectedTextRange!
textView.replace(textRenge, withText: emojiItem.emojiCode!)

图文混排

//根据图片创建属性字符串
let attachment = NSTextAttachment()
attachment.image = UIImage(named:"image.png")

//预先保存textView的font属性,后面有用
let textFont = textView.font!

//设置属性的尺寸
attachment.bounds = CGRect(x: 0, y: -4, width: textFont.lineHeight, height: textFont.lineHeight)
let attachmentStr = NSAttributedString(attachment: attachment)

//根据原先textView的字符串来创建可变的属性字符串
let attrMStr = NSMutableAttributedString(attributedString: textView.attributedText)

//找到光标的位置插入属性字符串
let range = textView.selectedRange
attrMStr.replaceCharacters(in: range, with: attachmentStr)

//重置textView的属性字符串
textView.attributedText = attrMStr

//并重置font,否则字体大小会变小,这也是前面要保存font属性的原因
textView.font = textFont

//插入属性字符串后,重置光标位置,不然光标会跑到所有字符串最后的位置
textView.selectedRange = NSRange(location: range.location + 1, length: 0)

results matching ""

    No results matching ""