Skip to content

Commit 9f8a149

Browse files
committed
Fix copy/paste text colors from others attributed sources.
1 parent fb48f65 commit 9f8a149

1 file changed

Lines changed: 18 additions & 3 deletions

File tree

Aztec/Classes/TextKit/TextViewPasteboardDelegate.swift

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ open class AztecTextViewPasteboardDelegate: TextViewPasteboardDelegate {
5858
guard let string = UIPasteboard.general.attributedString() else {
5959
return false
6060
}
61-
61+
string.loadLazyAttachments()
6262
let selectedRange = textView.selectedRange
6363
let storage = textView.storage
6464

@@ -69,9 +69,9 @@ open class AztecTextViewPasteboardDelegate: TextViewPasteboardDelegate {
6969
textView?.undoTextReplacement(of: originalText, finalRange: finalRange)
7070
})
7171

72-
string.loadLazyAttachments()
72+
let colorCorrectedString = fixColors(in: string, using: textView.textColor)
7373

74-
storage.replaceCharacters(in: selectedRange, with: string)
74+
storage.replaceCharacters(in: selectedRange, with: colorCorrectedString)
7575
textView.notifyTextViewDidChange()
7676

7777
let newSelectedRange = NSRange(location: selectedRange.location + string.length, length: 0)
@@ -80,6 +80,21 @@ open class AztecTextViewPasteboardDelegate: TextViewPasteboardDelegate {
8080
return true
8181
}
8282

83+
private func fixColors(in string: NSAttributedString, using baseColor: UIColor?) -> NSAttributedString {
84+
guard #available(iOS 13.0, *) else {
85+
return string
86+
}
87+
let colorToUse = baseColor ?? UIColor.label
88+
89+
let newString = NSMutableAttributedString(attributedString: string)
90+
newString.enumerateAttributes(in: newString.rangeOfEntireString, options: []) { (attributes, range, stop) in
91+
if attributes[.foregroundColor] == nil {
92+
newString.setAttributes([.foregroundColor: colorToUse], range: range)
93+
}
94+
}
95+
return newString
96+
}
97+
8398
/// Tries to paste raw text from the clipboard, replacing the selected range.
8499
///
85100
/// - Returns: True if the paste succeeds, false if it does not.

0 commit comments

Comments
 (0)