格式化UILabel上的金额

  1. 将 ¥123.456 变为红色
  2. 将 123 字体大小变大
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/// 获取标准格式的金额
/// - Parameters:
/// - str: 金额
/// - fontSize: 字体大小
func getAttributStrFormatMoney(str: String, fontSize: CGFloat , sizeOffSet:CGFloat?=4 , fontColor:UIColor?=UIColor.red) -> NSAttributedString{
let attributeStr = NSMutableAttributedString(string: str)

//let r = Range(0..<3) //old: let _ = NSRange(location: 0, length: 3)
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: fontColor!], range: signalNumRange)

// 查找 小数点
let pointRange = nsstr.range(of: ".")
// 设置 字体大小
let numFontSize = fontSize + sizeOffSet!
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: numFontSize), 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: numFontSize), range: numRange)
}
}
return attributeStr
}

使用

1
2
3
4
5
6
let str = String(format: "使用积分可抵¥%.2f", 123.456)
let attributeStr = getAttributStrFormatMoney(
str: str,
fontSize: 14.0
)
titleLab.attributedText = attributeStr

本文标题:格式化UILabel上的金额

文章作者:史彦超

发布时间:2016年10月11日 - 22:10

最后更新:2021年07月20日 - 16:07

原始链接:https://doingself.github.io/2016/10/11/2016-10-11-%E6%A0%BC%E5%BC%8F%E5%8C%96UILabel%E4%B8%8A%E7%9A%84%E9%87%91%E9%A2%9D/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Donate comment here