in the app TextEdit it is possible to convert Rich Text via the following procedure: Format, Make Plain Text. How can I perform this in Swift?
I use the NSPasteboard framework:
let pasteboard = NSPasteboard.general
...
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
...
In order to retrieve the clipboard contents:
var clipboardContents = ""
...
clipboardContents = pasteboard.string(forType: .string) ?? "Something went wrong"
The last statement yields Plain Text in the console window, however does not convert to it when using the clipboard contents in another application like TextExit etc. Your help is greatly appreciated!
You just need to get the rtf data from your pasteboard and then initialise a new attributed string with it. Once you have done that you can simply access the NSAttributedString string property:
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var simpleText: NSTextField!
@IBOutlet weak var labelField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
NSPasteboard.general.declareTypes([.rtf, .string], owner: nil)
}
@IBAction func pasteAction(_ sender: NSButton) {
guard let availableType = NSPasteboard.general.availableType(from: [.rtf, .string]) else { return }
switch availableType {
case .rtf:
print("Rich Text Data")
if let data = NSPasteboard.general.data(forType: .rtf),
let attributedString = NSAttributedString(rtf: data, documentAttributes: nil) {
labelField.attributedStringValue = attributedString
simpleText.stringValue = attributedString.string
}
case .string:
print("Simple Text")
if let string = NSPasteboard.general.string(forType: .string) {
simpleText.stringValue = string
}
default: break
}
}
}