简体   繁体   English

将字体添加到 NSMutableAttributedString 缺少 .font 属性的位置

[英]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.

相关问题 NSMutableAttributedString在更改字体时崩溃? - NSMutableAttributedString crashing on changing the font? 如何更改NSMutableAttributedString的默认字体和字体大小 - how to change the default font and font size of NSMutableAttributedString 无法在NSMutableAttributedString中设置自定义字体 - unable to set custom font in NSMutableAttributedString NSMutableAttributedString字体大小意外更改 - NSMutableAttributedString font size changes by accident NSMutableAttributedString中的Swift替换字体大小 - Swift replacement font size in NSMutableAttributedString 在iOS中添加字体许可证的位置 - Where to add font license in iOS 在NSTextStorage NSMutableAttributedString的末尾设置新字体 - Set new font at end of NSTextStorage NSMutableAttributedString iOS:更改NSMutableAttributedString的字体高度而不更改字体宽度? - iOS: Change NSMutableAttributedString's Font Height Without Changing Font Width? 调整与UILabel的框架高度成比例的NSMutableAttributedString字体大小 - Adjust font size of NSMutableAttributedString proportional to UILabel's frame height 更改字体属性后如何使用NSMutableAttributedString维护UITextview的位置 - How to maintain the position of the UITextview with NSMutableAttributedString after changing font attriibutes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM