格式化Label的金额

  1. 将 ¥123.456 变为红色
  2. 将 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

转载于:https://my.oschina.net/asjoker/blog/907177

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值