- 将 ¥123.456 变为红色
- 将 123 字体大小变大
let str = "金额:¥12.3456789"
let attributeStr = NSMutableAttributedString(string: str)
let nsstr = str as NSString
// 查找金额
let signalRange = nsstr.range(of: "¥")
if signalRange.length > 0 {
let signalNumRange = NSRange(location: signalRange.location, length: attributeStr.length - signalRange.location)
// 设置为字体颜色
attributeStr.setAttributes([NSForegroundColorAttributeName: UIColor.red], range: signalNumRange)
// 查找 小数点
let pointRange = nsstr.range(of: ".")
if pointRange.length > 0 {
let numRange = NSRange(location: signalRange.location + signalRange.length, length: pointRange.location + pointRange.length - (signalRange.location + signalRange.length))
// 设置 字体大小
attributeStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 20), range: numRange)
}else{
let numRange = NSRange(location: signalRange.location + signalRange.length, length: attributeStr.length - (signalRange.location + signalRange.length) )
// 设置 字体大小
attributeStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 20), range: numRange)
}
}
attributeStr