Swift实现富文本
2018-04-18 本文已影响56人
何以消摇
在做搜索的时候,我们需要把搜索的关键字全部都进行高亮处理,这个时候就需要用到富文本处理。
以下是我封装的方法,直接调用就可以了
extension NSMutableAttributedString {
static func highLightText(_ normal: String, highLight: String, font: UIFont, color: UIColor, highLightColor: UIColor) -> NSMutableAttributedString {
//定义富文本即有格式的字符串
let attributedStrM : NSMutableAttributedString = NSMutableAttributedString()
let strings = normal.components(separatedBy: highLight)
for i in 0..<strings.count {
let item = strings[i]
let dict = [NSFontAttributeName: font,
NSForegroundColorAttributeName: color]
let content = NSAttributedString(string: item, attributes: dict)
attributedStrM.append(content)
if i != strings.count - 1 {
let dict1 = [NSFontAttributeName: font,
NSForegroundColorAttributeName: highLightColor]
let content2 = NSAttributedString(string: highLight,
attributes: dict1)
attributedStrM.append(content2)
}
}
return attributedStrM
}
}
这里的NSFontAttributeName 为修改font 所对应的 key,类型为NSAttributedStringKey,font为他的值,类型为UIFont
NSForegroundColorAttributeName为修改前景字体颜色(简单可以理解为字体颜色)
一般修改这两个属性就够了,其他对应属性可以参看官方文档,可能有些参数名会随着swift的更新而修改,不过基本换汤不换药
然后可以再简化一下调用,把字体颜色都直接写入进去,传入字符串和需要高亮的字符串就可以了
extension NSMutableAttributedString {
static func highLightText(_ normal: String, highLight: String) -> NSMutableAttributedString{
let attributedStrM = highLightText(normal,
highLight: highLight,
font: UIFont.systemFont(ofSize: 16),
color: .black,
highLightColor: .red)
return attributedStrM
}
}
调用
nameL.attributedText = NSMutableAttributedString.highLightText(cellModel.name, highLight: model.highLight)
//注意设置的是attributedText,下面这行代码记得注释或者删除
//nameL.text = cellModel.name
NSMutableAttributedString详解及OC版本请参照本文