nsattribatedstring更改字体大小

发布于 2025-02-08 07:21:47 字数 102 浏览 2 评论 0原文

我有一个NSATTRIBDERSTRING,它可能具有多个具有不同字体样式和其他属性的子弹。如何修改整个属性字符串字体的大小?将字体尺寸设置为20,应将字符串中所有字体的所有字体设置为20。

I have an NSAttributedString which may have multiple subranges with different font styles and other attributes. How do I modify the size of font for the whole attributed string? Setting a font size of 20 should set pointSize of all fonts in the string to 20.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

日暮斜阳 2025-02-15 07:21:47

通过这些扩展,您将能够轻松地更改所有子弹中nsattributedString的字体大小,而其他字体参数则相同。

用法

let label: UILabel = ...
let string: NSAttributedString = ...

label.attributedText = string.mutable.setFontSize(20)

扩展

extension NSMutableAttributedString {
    func setFontSize(_ fontSize: CGFloat) {
        beginEditing()
        enumerateAttribute(.font, in: completeRange) { value, range, _ in
            guard
                let fontFromAttribute = value as? UIFont,
                let descriptor = fontFromAttribute.fontDescriptor
                    .withSymbolicTraits(fontFromAttribute.fontDescriptor.symbolicTraits)
            else { return }
            let font = UIFont(descriptor: descriptor, size: fontSize)
            addAttribute(.font, value: font, range: range)
        }
        endEditing()
    }
}
extension NSAttributedString {
    var mutable: NSMutableAttributedString {
        NSMutableAttributedString(attributedString: self)
    }

    var completeRange: NSRange { 
        NSRange(location: 0, length: self.length) 
    }
}

With these extensions you will be able to easily change font size of the NSAttributedString in all of the subranges leaving other font parameters the same.

Usage

let label: UILabel = ...
let string: NSAttributedString = ...

label.attributedText = string.mutable.setFontSize(20)

Extensions

extension NSMutableAttributedString {
    func setFontSize(_ fontSize: CGFloat) {
        beginEditing()
        enumerateAttribute(.font, in: completeRange) { value, range, _ in
            guard
                let fontFromAttribute = value as? UIFont,
                let descriptor = fontFromAttribute.fontDescriptor
                    .withSymbolicTraits(fontFromAttribute.fontDescriptor.symbolicTraits)
            else { return }
            let font = UIFont(descriptor: descriptor, size: fontSize)
            addAttribute(.font, value: font, range: range)
        }
        endEditing()
    }
}
extension NSAttributedString {
    var mutable: NSMutableAttributedString {
        NSMutableAttributedString(attributedString: self)
    }

    var completeRange: NSRange { 
        NSRange(location: 0, length: self.length) 
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文