我有一个包含金额的字符串值,其中我将小数部分指定为“,”之后,并且我想将“,”之后部分的字体更改为其他部分的一半
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
}
你需要更换
let startIndex = text.index(commaRange.upperBound, offsetBy: 1)
与
let startIndex = commaRange.upperBound
这是一个测试演示
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let bl = UILabel(frame: UIScreen.main.bounds)
bl.attributedText = getText(text: "123323232333,454", size: 20)
view.addSubview(bl)
}
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 = commaRange.upperBound
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
}
}