如何检查剪贴板中是否有内容

How to check if there is something on the clipboard

如何检查剪贴板中是否有内容?

如果剪贴板上有东西,则执行某个动作,如果没有,则执行另一个动作(如示例代码所示)

if (if in the clipboard, that is, then open the VC) {
        let modalViewController = self.storyboard?.instantiateViewController(withIdentifier: "Clipboard") as? ClipboardViewController
        modalViewController?.modalPresentationStyle = .overCurrentContext
        self.present(modalViewController!, animated: true, completion: nil)
} else (if the clipboard is empty then) {
        let alert = UIAlertController(title: "Clipboard is Empty", message: "It's recommended you bring your towel before continuing.", preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: nil))
        alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))

        self.present(alert, animated: true)
}

你应该使用 UIPasteboard class.

if let value = UIPasteboard.general.string {
    // there is value in clipboard
} else {
    // clipboard is empty
}

从 iOS 10 开始,您应该使用 UIPasteboard 属性,例如 hasStrings 来检查粘贴板上是否存在特定数据类型:

var hasStrings: Bool

Returns a Boolean value indicating whether or not the strings property contains a nonempty array.


来自文档:

Starting in iOS 10, the UIPasteboard class provides properties for directly checking whether specific data types are present on a pasteboard, described in Checking for Data Types on a Pasteboard. Use these properties, rather than attempting to read pasteboard data, to avoid causing the system to needlessly attempt to fetch data before it is needed or when the data might not be present. For example, you can use the new hasStrings property to determine whether to present a string-data Paste option in the user interface, using code like this:

if UIPasteboard.general.hasStrings {
    // Enable string-related control...
    if let string = UIPasteboard.general.string {
        // use the string here
    }
}

还有一些属性可以检查数据类型;

var hasColors: Bool

Returns a Boolean value indicating whether or not the colors property contains a nonempty array.


var hasImages: Bool

Returns a Boolean value indicating whether or not the images property contains a nonempty array.


var hasURLs: Bool

Returns a Boolean value indicating whether or not the urls property contains a nonempty array.