如何编辑复制到 UIPasteboard 中的文本

How can I edit the text copied into UIPasteboard

我正在尝试操作用户从 UILabel 复制到 UIPasteboard 中的文本,但找不到示例。

这是一个完整的示例视图控制器,用于实现您想要实现的目标(阅读评论以了解正在发生的事情...):

import UIKit
import MobileCoreServices

class ViewController: UIViewController {

  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    // add an observer (self) for whenever the pasteboard contents change
    // this is going to be called whenever the user copies text for example
    NSNotificationCenter
      .defaultCenter()
      .addObserver(
        self,
        selector: "pasteboardChanged:",
        name: UIPasteboardChangedNotification,
        object: nil)


  }

  override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    // make sure to pair addition/removal of observers
    // we add the observer in viewWillAppear:, so let's 
    // remove it in viewWillDisappear: (here)
    NSNotificationCenter.defaultCenter().removeObserver(self)

  }

  // this will be called whenever the pasteboard changes
  // we specified this function in our observer registration above
  @objc private func pasteboardChanged(notification: NSNotification){

    // this is what the user originally copied into the pasteboard
    let currentPasteboardContents = UIPasteboard.generalPasteboard().string
    // you can now modify whatever was copied
    let newPasteboardContent = " ----- MODIFY THE PASTEBOARD CONTENTS (\(currentPasteboardContents)) AND SET THEM HERE ---------"

    // before we can actually set the new pasteboard contents, we need to make 
    // sure that this method isn't called recursively (we will change the pasteboard's
    // contents, so if we don't remove ourselves from the observer, this method will 
    // be called over and over again, ending up leaving us in an endless loop)
    NSNotificationCenter
      .defaultCenter()
      .removeObserver(
        self,
        name: UIPasteboardChangedNotification,
        object: nil)

    // GREAT! We unregistered ourselves as an observer, now's the time
    // to change the pasteboard contents to whatever we want!
    UIPasteboard.generalPasteboard().string = newPasteboardContent

    // we want to get future changes to the pasteboard, so let's re-add
    // ourselves as an observer
    NSNotificationCenter
      .defaultCenter()
      .addObserver(
        self,
        selector: "pasteboardChanged:",
        name: UIPasteboardChangedNotification,
        object: nil)

  }

}

确保你 import MobileCoreServices 否则你将无法使用某些代码...

祝你好运!

编辑

如果您想少走 "hacky" 路线,我建议您进入 UIMenuController。这里有一个不错的tutorial/guide:

http://nshipster.com/uimenucontroller/