You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改字符串中逗号后内容的字体大小为原字体的一半

金额字符串小数部分半号字体实现方案

针对以逗号分隔整数与小数位的金额字符串,我们可以通过富文本属性将小数部分的字体大小设置为其余部分的一半,以下是Swift的具体实现代码:

private func getText(text: String, size: CGFloat) -> NSAttributedString {
    let attributedString = NSMutableAttributedString(
        string: text,
        attributes: [
            .font: UIFont.themeFont(ofSize: size, weight: .medium)
        ]
    )
    
    if let commaRange = text.range(of: ",") {
        let startIndex = text.index(commaRange.upperBound, offsetBy: 1)
        let substring = text[startIndex...]
        
        attributedString.addAttributes(
            [
                .font: UIFont.themeFont(ofSize: size / 2, weight: .medium)
            ],
            range: NSRange(location: text.distance(from: text.startIndex, to: startIndex), length: substring.count)
        )
    }
    
    return attributedString
}

代码逻辑说明:

  • 先初始化带有全局默认字体(传入的size尺寸)的可变富文本
  • 通过range(of: ",")定位金额字符串里的逗号位置
  • 计算逗号后小数部分的起始索引和长度,为该区间文本追加字体大小为size/2的属性
  • 返回处理完成的富文本对象

内容的提问来源于stack exchange,提问作者HBK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 10:52:02