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
}
2
Answers
The
upperbound
of a range is the index after the index of the last character in the range, so the offset is not needed.The
substring
is not needed either, and use theaddAttribute(_:value:range:)
API to apply one attributeOr determine the range with Regex
A still more convenient way is Swift’s native
AttributedString
Side note: Converting
Range<String.Index>
toNSRange
withNSRange(location:length:)
is strongly discouraged.I think it would be fun to provide a solution using modern Swift. Attributed strings are now native (AttributedString). Regular expressions are now native (Regex). So we can write it like this: