我有一个像"abc1abc1"
这样的字符串。
我要做的是将字符串的每个数字加粗。我在下面绘制了代码。它通过分离字符串的每个字符并将它们放入数组中来工作。然后,在循环中,如果每个字符都包含一个Int()
,则该字符将以粗体显示。
但是,当有两个相同的Int时,就会出现问题。在上面的字符串中,1
有2个字符,因此代码只会将第一个字符加粗。
// Bold the numbers
let fullString = "abc1abc1"
let characters = Array(fullString)
let mutableString = NSMutableAttributedString(string: fullString)
for item in characters {
let string = String(item)
let decimalCharacters = CharacterSet.decimalDigits
let decimalRange = string.rangeOfCharacter(from: decimalCharacters)
if decimalRange != nil {
let str = NSString(string: fullString)
let range = str.range(of: string)
mutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIFont.systemFont(ofSize: 18, weight: .heavy), range: range)
}
}
instructionsLabel.attributedText = mutableString
// characters = ["a", "b", "c", "1", "a", "b", "c", "1"]
// range of ints returns {3, 1} and {3, 1}
// range of ints SHOULD return {3, 1} and {7, 1}
答案 0 :(得分:1)
尝试一下:
let fullString = "abc1abc1"
let range = NSRange(location: 0, length: (fullString as NSString).length)
let mutableString = NSMutableAttributedString(string: fullString)
let regex = try! NSRegularExpression(pattern: "[0-9]")
let matches = regex.matches(in: fullString, range: range)
for match in matches {
mutableString.addAttributes([.font: UIFont.systemFont(ofSize: 18, weight: .heavy)], range: match.range)
}
instructionsLabel.attributedText = mutableString