Search code examples
iosswiftnsattributedstring

How can I change the font after "," in string


I have a string value containing an amount, where I specified the decimal part as after "," and I want to change the font of the part after "," to be half of the other part

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
}

Solution

  • private func getText(text: String, size: CGFloat) -> NSAttributedString {
        let attributedText = NSMutableAttributedString(string: text)
        let comaRange = (text as NSString).range(of: ",")
        let afterComaRange = NSRange(location: comaRange.location  + 1 , length: text.count - comaRange.location - 1)
        let font = UIFont.themeFont(ofSize: size, weight: .medium)
        let changedFont = UIFont.themeFont(ofSize: 14, weight: .medium)
        attributedText.addAttribute(.font, value: font, range: NSRange(location: 0, length: comaRange.location))
        attributedText.addAttribute(.font, value: changedFont, range: afterComaRange)
        return attributedText
    }
    

    this is my answer and it's work.