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

时间:2016-02-29 22:33:40

标签: swift uilabel edit uipasteboard

我正在尝试操纵用户从UILabel复制到UIPasteboard但未找到示例的文本。

1 个答案:

答案 0 :(得分:3)

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

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。这里有一个很好的教程/指南:

  

http://nshipster.com/uimenucontroller/