value
аргумент, переданный к закрытию enumerateAttribute
с NSFontAttributeName
представляет собой UIFont
связанный с range
. Итак, вам просто нужно проверить, выделен ли шрифт или нет, и собрать диапазон.
//Find ranges of bold words.
let attributedText = descriptionTextView.attributedText!
var boldRanges: [NSRange] = []
attributedText.enumerateAttribute(NSFontAttributeName, in: NSRange(0..<attributedText.length), options: .longestEffectiveRangeNotRequired) {
value, range, stop in
//Confirm the attribute value is actually a font
if let font = value as? UIFont {
//print(font)
//Check if the font is bold or not
if font.fontDescriptor.symbolicTraits.contains(.traitBold) {
//print("It's bold")
//Collect the range
boldRanges.append(range)
}
}
}
вы можете изменить цвет в этих диапазонах обычным способом:
//Replace their colors.
let mutableAttributedText = attributedText.mutableCopy() as! NSMutableAttributedString
for boldRange in boldRanges {
mutableAttributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: boldRange)
}
descriptionTextView.attributedText = mutableAttributedText
любым другим способом, кроме атрибута текста? – user3395433