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.
Asked
Active
Viewed 906 times
0
-
This might help: https://stackoverflow.com/a/45960418/4490923 – Asteroid Jun 15 '22 at 14:54
-
1https://stackoverflow.com/questions/56102521/change-only-fontsize-of-nsattributedstring ? – Larme Jun 15 '22 at 15:06
1 Answers
2
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)
}
}

Witek Bobrowski
- 3,749
- 1
- 20
- 34
-
why can't I just override it? I think `removeAttribute(.font, range: range)` is useless. – Elevo Jun 15 '22 at 15:56
-