在 Swift 中以编程方式将富文本转换为纯文本
Convert Rich Text to Plain Text programmatically in Swift
在应用程序 TextEdit 中,可以通过以下过程转换 Rich Text:格式化,制作纯文本。如何在 Swift 中执行此操作?
我使用 NSPasteboard 框架:
let pasteboard = NSPasteboard.general
...
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
...
为了检索剪贴板内容:
var clipboardContents = ""
...
clipboardContents = pasteboard.string(forType: .string) ?? "Something went wrong"
最后一条语句在控制台中生成纯文本 window,但是在其他应用程序(如 TextExit 等)中使用剪贴板内容时不会转换为纯文本。非常感谢您的帮助!
您只需要从粘贴板中获取 rtf 数据,然后用它初始化一个新的属性字符串。完成后,您可以简单地访问 NSAttributedString 字符串 属性:
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
}
}
}
在应用程序 TextEdit 中,可以通过以下过程转换 Rich Text:格式化,制作纯文本。如何在 Swift 中执行此操作?
我使用 NSPasteboard 框架:
let pasteboard = NSPasteboard.general
...
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
...
为了检索剪贴板内容:
var clipboardContents = ""
...
clipboardContents = pasteboard.string(forType: .string) ?? "Something went wrong"
最后一条语句在控制台中生成纯文本 window,但是在其他应用程序(如 TextExit 等)中使用剪贴板内容时不会转换为纯文本。非常感谢您的帮助!
您只需要从粘贴板中获取 rtf 数据,然后用它初始化一个新的属性字符串。完成后,您可以简单地访问 NSAttributedString 字符串 属性:
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
}
}
}