【问题标题】:iOS Swift: How to access selected text in WKWebViewiOS Swift:如何访问 WKWebView 中的选定文本
【发布时间】:2018-11-13 13:17:58
【问题描述】:

我希望能够使用菜单按钮将所选文本从 WKWebView 中的网页复制到粘贴板。我想将粘贴板上的文本放入第二个视图控制器中的文本视图中。如何访问和复制 WKWebView 中的选定文本?

【问题讨论】:

  • Objective C 中另一个类似问题的以下链接。可以帮助您将其转换为 swift。 stackoverflow.com/q/50846404/2641380
  • @Zach 如果您找到了解决方案,请发布。这对我有很大的帮助,谢谢!

标签: swift wkwebview uipasteboard nspasteboard


【解决方案1】:

斯威夫特 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")
    }
}

因为我不知道您的确切项目或用例,所以您可能需要稍微更改代码,但我希望我为您提供了项目所需的部分。如果我遗漏了什么,请发表评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-22
    • 2020-04-12
    • 1970-01-01
    • 2018-11-23
    • 2022-01-02
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    相关资源
    最近更新 更多