@@ -3,19 +3,23 @@ import UIKit
33
44public extension NSMutableAttributedString {
55
6+ /// Replace all instances of the .font attribute that belong to the same family for the new font, trying to keep the same symbolic traits
7+ /// - Parameter font: the original font to be replaced
8+ /// - Parameter newFont: the new font to use.
69 func replace( font: UIFont , with newFont: UIFont ) {
7- let fullRange = NSRange ( location: 0 , length: self . length)
10+ let fullRange = NSRange ( location: 0 , length: length)
811
9- self . beginEditing ( )
10- self . enumerateAttributes ( in: fullRange, options: [ ] ) { ( attributes, subrange, stop) in
11- if let currentFont = attributes [ . font] as? UIFont , currentFont. familyName == font. familyName {
12- var replacementFont = newFont
13- if let fontDescriptor = newFont. fontDescriptor. withSymbolicTraits ( currentFont. fontDescriptor. symbolicTraits) {
14- replacementFont = UIFont ( descriptor: fontDescriptor, size: currentFont. pointSize)
15- }
16- self . addAttribute ( . font, value: replacementFont, range: subrange)
12+ beginEditing ( )
13+ enumerateAttributes ( in: fullRange, options: [ ] ) { ( attributes, subrange, stop) in
14+ guard let currentFont = attributes [ . font] as? UIFont , currentFont. familyName == font. familyName else {
15+ return
1716 }
17+ var replacementFont = newFont
18+ if let fontDescriptor = newFont. fontDescriptor. withSymbolicTraits ( currentFont. fontDescriptor. symbolicTraits) {
19+ replacementFont = UIFont ( descriptor: fontDescriptor, size: currentFont. pointSize)
20+ }
21+ addAttribute ( . font, value: replacementFont, range: subrange)
1822 }
19- self . endEditing ( )
23+ endEditing ( )
2024 }
2125}
0 commit comments