[英]Add font to NSMutableAttributedString where .font attribute is missing
I want to apply a specific font to an NSMutableAttributedString
where no .font
attribute is applied.我想将特定字体应用于未应用
.font
属性的NSMutableAttributedString
。 How could I achieve that?我怎么能做到这一点? I tried enumerating the attributes that contain a font and extracting the ranges but I am kind of lost to the complexity of finding the ranges that don't contain a font attribute since I think I must handle intersections or possible unknown scenarios.
我尝试枚举包含字体的属性并提取范围,但我有点迷失于查找不包含字体属性的范围的复杂性,因为我认为我必须处理交叉点或可能的未知场景。 Is there a simple way to do it?
有没有简单的方法来做到这一点? What I did until now:
到目前为止我所做的:
var allRangesWithFont = [NSRange]()
let stringRange = NSRange(location: 0, length: length)
beginEditing()
enumerateAttribute(.font,
in: stringRange,
options: .longestEffectiveRangeNotRequired) { (value, range, stop) in
if let f = value as? UIFont {
allRangesWithFont.append(range)
}
}
Change your way of thinking, instead, check if the font is not there, and apply your new font directly.改变你的思维方式,相反,检查字体是否不存在,然后直接应用你的新字体。
With attrStr
being your NSMutableAttributedString
, and newFont
the font you want to apply. attrStr
是您的NSMutableAttributedString
,而newFont
是您要应用的字体。
let newFont = UIFont.italicSystemFont(ofSize: 15)
attrStr.enumerateAttribute(.font, in: NSRange(location: 0, length: attrStr.length), options: []) { value, subrange, pointeeStop in
guard value == nil else { return }
attrStr.addAttribute(.font, value: newFont, range: subrange)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.