收到有关swift剪贴板更改的通知

时间:2015-04-08 13:46:35

标签: swift clipboard

swift中有剪贴板更改事件吗? 如何在iOS应用程序中更改剪贴板时收到通知 感谢

3 个答案:

答案 0 :(得分:5)

这是一个可复制的 swift 3.0 版本

NotificationCenter.default.addObserver(self, selector: #selector(clipboardChanged),
                                       name: NSNotification.Name.UIPasteboardChanged , object: nil)

此外,如果您想在此活动中获取剪贴板中的文字,

func clipboardChanged(){
    let pasteboardString: String? = UIPasteboard.general.string
    if let theString = pasteboardString {
        print("String is \(theString)")
        // Do cool things with the string
    }
}

答案 1 :(得分:4)

您可以按照以下链接中所述捕获UIPastedboardChangedNotification:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIPasteboard_Class/index.html#//apple_ref/c/data/UIPasteboardChangedNotification

示例:(无法使代码正确显示,我已粘贴图像。

  1. 在AppDelegate中向didFinishLaunchingwithOptions回调添加通知

  2. 添加函数以便在UIPastedboardChangedNotification发送给您时处理AppDelegate

  3. enter image description here

答案 2 :(得分:0)

解决方案:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // ...

    // Clipboard
    NotificationCenter.default.addObserver(self, selector: #selector(internalClipboardChanged), name: UIPasteboard.changedNotification, object: nil)

    // ...
}

func sceneDidBecomeActive(_ scene: UIScene) {
    // ...
    self.clipboardChanged()
}

// CLIPBOARD
@objc func internalClipboardChanged() {
    // ...
    self.clipboardChanged()
}

func clipboardChanged() {
    if (UIPasteboard.general.hasImages) {
        self.controller!.clipboardImage = UIPasteboard.general.image
    } else {
        self.controller!.clipboardImage = nil
    }
}