斯威夫特 4
您可以使用以下行访问通用粘贴板:
let generalPasteboard = UIPasteboard.general
在视图控制器中,您可以添加观察者来观察何时将某些内容复制到粘贴板。
override func viewDidLoad() {
super.viewDidLoad()
// https://stackoverflow.com/questions/35711080/how-can-i-edit-the-text-copied-into-uipasteboard
NotificationCenter.default.addObserver(self, selector: #selector(pasteboardChanged(_:)), name: UIPasteboard.changedNotification, object: generalPasteboard)
}
override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(UIPasteboard.changedNotification)
super.viewDidDisappear(animated)
}
@objc
func pasteboardChanged(_ notification: Notification) {
print("Pasteboard has been changed")
if let data = generalPasteboard.data(forPasteboardType: kUTTypeHTML as String) {
let dataStr = String(data: data, encoding: .ascii)!
print("data str = \(dataStr)")
}
}
在上面的 pasteboardChanged 函数中,我以 HTML 格式获取数据,以便在 WKWebView 的第二个控制器中显示复制的格式化文本。您必须导入 MobileCoreServices 才能引用 UTI kUTTypeHTML。要查看其他 UTI,请查看以下链接:Apple Developer - UTI Text Types
import MobileCoreServices
在您最初的问题中,您提到要将复制的内容放入第二个文本视图中。如果要保留格式,则需要将复制的数据作为 RTFD 获取,然后将其转换为属性字符串。然后设置 textview 显示属性字符串。
let rtfdStringType = "com.apple.flat-rtfd"
// Get the last copied data in the pasteboard as RTFD
if let data = pasteboard.data(forPasteboardType: rtfdStringType) {
do {
print("rtfd data str = \(String(data: data, encoding: .ascii) ?? "")")
// Convert rtfd data to attributedString
let attStr = try NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtfd], documentAttributes: nil)
// Insert it into textview
print("attr str = \(attStr)")
copiedTextView.attributedText = attStr
}
catch {
print("Couldn't convert pasted rtfd")
}
}
因为我不知道您的确切项目或用例,所以您可能需要稍微更改代码,但我希望我为您提供了项目所需的部分。如果我遗漏了什么,请发表评论。