Skip to content

Commit 3d0c2e8

Browse files
committed
Improve replaceFont code and add some documentation.
1 parent 31e70a0 commit 3d0c2e8

1 file changed

Lines changed: 14 additions & 10 deletions

File tree

Aztec/Classes/Extensions/NSMutableAttributedString+ReplaceAttributes.swift

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,23 @@ import UIKit
33

44
public 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

Comments
 (0)