我希望能够使用菜单按钮将所选文本从WKWebView中的网页复制到粘贴板。我想将粘贴板中的文本放入第二个视图控制器的文本视图中。如何访问和复制WKWebView中的选定文本?
发布于 2018-12-19 18:31:55
Swift 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。要查看其他实用工具,请参阅以下链接:Apple Developer - UTI Text Types
import MobileCoreServices
在最初的问题中,您提到要将复制的内容放入第二个文本视图中。如果您希望保留格式,则需要将复制的数据作为RTFD获取,然后将其转换为属性字符串。然后设置文本视图以显示属性字符串。
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")
}
}
因为我不知道您的确切项目或用例,所以您可能需要稍微修改一下代码,但我希望我为您提供了项目所需的部分。如果我遗漏了什么,请指教。
https://stackoverflow.com/questions/53281885
复制相似问题