知识点
拖一个UILabel控件到storyboard中,我们即将对它进行图文混排,属性名为:demoLabel
直接上简单的示例代码:
// 创建2个属性字符串
let attrStr1 = NSAttributedString(string: "LXF", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
let attrStr2 = NSAttributedString(string: "Demo", attributes: [NSForegroundColorAttributeName : UIColor.blueColor()])
// 图文混排
let attacment = NSTextAttachment()
attacment.image = UIImage(named: "d_aoteman") // 设置要显示的图片
let font = demoLabel.font // 取出demoLabel控制文字大小
attacment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
let attrImageStr = NSAttributedString(attachment: attacment) // 设置图片显示的大小及位置
// 拼接图文
let attrMStr = NSMutableAttributedString()
attrMStr.appendAttributedString(attrStr1)
attrMStr.appendAttributedString(attrImageStr)
attrMStr.appendAttributedString(attrStr2)
// 显示属性字符串
demoLabel.attributedText = attrMStr
效果图:
知识点应用案例
注意:如果将上面的知识活用于即时插入表情到现有文字中,你会发现有如下图的情况
后面的表情变小了(文字也会!),这是使用了属性字符串的问题,解决该问题也比较简单,在每次显示属性字符串之后重置demoLabel的font就行了
demoLabel.font = font
案例代码:
@IBOutlet weakvar textView: UITextView!
// 插入表情:图文混排
// 1.根据图片路径创建属性字符串
let attachment = NSTextAttachment()
attachment.image = UIImage(contentsOfFile: emoticon.pngPath!) // 设置要显示的表情
let font = textView.font! // 取出当前字体
attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight) // 调整插入的表情的大小及位置
let attrImageStr = NSAttributedString(attachment: attachment)
// 2.创建可变的属性字符串(为当前已有的图文)
let attrMstr = NSMutableAttributedString(attributedString: textView.attributedText)
// 3.将图片属性字符串,替换到可变属性字符串的某一个位置
// 3.1.获取光标所在的位置
let range = textView.selectedRange
// 3.2.替换属性字符串
attrMstr.replaceCharactersInRange(range, withAttributedString: attrImageStr)
// 显示属性字符串
textView.attributedText = attrMstr
// 解决问题:插入表情后,再插入表情或文字时,表情或文字会变小
// 将文字的大小重置
textView.font = font
// 解决问题:在文字中间插入表情后,光标会跑到文字最后
// 将光标设置回原来位置 + 1
textView.selectedRange = NSRange(location: range.location + 1, length: 0)