iOS UIPasteboard

In this tutorial, we’ll be discussing and implementing the UIPasteboard class in our iOS Application.

在本教程中,我们将在iOS应用程序中讨论和实现UIPasteboard类。

UIPasteboard (UIPasteboard)

The UIPasteboard class provides a clipboard and is used to share data within the app and from one application to the other.

UIPasteboard类提供一个剪贴板,用于在应用程序内以及一个应用程序与另一个应用程序之间共享数据。

Using a UIPasteboard, you can copy paste text, url, images and other data types. UIPasteboard has a system-wide clipboard which holds the data you’ve copied.

使用UIPasteboard,您可以复制粘贴的文本,URL,图像和其他数据类型。 UIPasteboard有一个系统范围的剪贴板,用于保存您复制的数据。

Following are the important helper properties and functions of a UIPasteboard:

以下是UIPasteboard的重要帮助程序属性和功能:

general property is used to retrieve the system-wide UIPasteboard.

general属性用于检索系统范围的UIPasteboard。

let pasteboard = UIPasteboard.general

Creating your own Named Pasteboard:

创建自己的命名粘贴板:

let pasteboard = UIPasteboard.init(name: UIPasteboard.Name(rawValue: "pasteboard_name"), create: true)

Inside the init method, we pass two arguments: name and create.
Using the above statement we can retrieve the same named Pasteboard.

init方法内部,我们传递了两个参数: namecreate
使用上面的语句,我们可以检索相同名称的Pasteboard。

The create argument requires a Bool value. If it is set as true, then the Pasteboard would be created if it doesn’t exist already.

create参数需要一个Bool值。 如果将其设置为true,则将创建粘贴面板(如果尚不存在)。

UIPasteboard.withUniqueName() returns a unique UIPasteboard. This returns a Pasteboard which is visible in all your apps having the same APP ID.

UIPasteboard.withUniqueName()返回唯一的UIPasteboard。 这会返回一个粘贴板,在所有具有相同APP ID的应用程序中可见。

To copy a String/URL/UIColor/UIImage to the Pasteboard, we simply do:

要将String / URL / UIColor / UIImage复制到粘贴板,我们只需执行以下操作:

UIPasteboard.general.string = "String"
UIPasteboard.general.url = URL(string: "https://www.google.com")
UIPasteboard.general.color = UIColor.red
UIPasteboard.general.image = UIImage(named : "sample.png")
strings, stringscolors, colorsurls, urlsimages images属性

We can set values to the Named Pasteboard, or even the general pasteboard instance using the following functions as well:

我们还可以使用以下功能为“命名粘贴板”甚至常规粘贴板实例设置值:

  • func setValue(Any, forPasteboardType: String) – This is used to set any instance such as string, date, url, model object. We pass the type of the value in the second argument.

    func setValue(Any, forPasteboardType: String) –用于设置任何实例,例如字符串,日期,URL,模型对象。 我们在第二个参数中传递值的类型。
  • func setData(Data, forPasteboardType: String) – This is used to set Data which is generally an image/video or a File type.

    func setData(Data, forPasteboardType: String) –用于设置数据,通常是图像/视频或文件类型。

The following functions return the data for the type passed in:

以下函数返回传入类型的数据:

  • func data(forPasteboardType: String) -> Data?

    func data(forPasteboardType: String) -> Data?
  • func value(forPasteboardType: String) -> Any?

    func value(forPasteboardType: String) -> Any?

func itemSet(withPasteboardTypes: [String]) -> IndexSet? returns a Set containing values of all the types passed in the array.

func itemSet(withPasteboardTypes: [String]) -> IndexSet? 返回一个Set,其中包含在数组中传递的所有类型的值。

In order to check whether the Pasteboard has a value of the certain type we can do:

为了检查粘贴板是否具有某种类型的值,我们可以执行以下操作:

  • pasteboard.hasStrings

    pasteboard.hasStrings
  • pasteboard.hasURLs

    pasteboard.hasURLs
  • pasteboard.hasColors

    pasteboard.hasColors
  • pasteboard.hasImages

    pasteboard.hasImages

func setItems([[String : Any]], options: [UIPasteboard.OptionsKey : Any] = [:]) is used to add a dictionary of items to the Pasteboard. We can set privacy options on the items as well The options arguments is a dictionary of key-value pairs as well. Following are the two most commonly used options:

func setItems([[String : Any]], options: [UIPasteboard.OptionsKey : Any] = [:])用于将项目字典添加到Pasteboard。 我们也可以在项目上设置隐私选项。options参数也是键-值对的字典。 以下是两个最常用的选项:

  • expiration – The date after which the items would be cleared from the Pasteboard

    expiration –从粘贴板上清除项目的日期
  • localOnly – By default the Pasteboard is universal. That means, if the handoff feature is enabled on your iOS Device, the pasteboard can be used across your Apple Devices. To keep the Pasteboard restricted in your current device only, set localOnly to true

    localOnly –默认情况下,粘贴板是通用的。 这意味着,如果在iOS设备上启用了切换功能,则可以在所有Apple设备上使用粘贴板。 若要仅在您的当前设备中限制localOnly ,请将localOnly设置为true

In the next section, we’ll be creating an iOS Application with the above-learned methods and properties in use:

在下一节中,我们将使用上面学习的方法和属性创建一个iOS应用程序:

项目情节提要 (Project Storyboard)

Our ViewController UI consists of UIStackViews with nested StackViews as shown in the Storyboard below:

我们的ViewController UI由带有嵌套StackView的UIStackView组成,如下面的情节提要中所示:

We’ll be doing copy paste of String, URL and an Image that we’ve added in the assets folder.

我们将复制粘贴在资源文件夹中的字符串,URL和图像。

  • Top StackView – Consists of UITextField. Here the copy paste would be done on String type.

    顶部StackView –包含UITextField。 在这里,复制粘贴将在String类型上完成。
  • Middle StackView – Consists of UILabel. Here the copy paste would be done on URL type.

    中间StackView –包含UILabel。 在这里,复制粘贴将在URL类型上完成。
  • Bottom StackView – Consists of UIImage. Here the copy paste would be done on Image type.

    底部StackView –包含UIImage。 这里复制粘贴将在图像类型上完成。

(Code)

The code for the ViewController.swift class is given below:

下面给出了ViewController.swift类的代码:

import UIKit
import MobileCoreServices

class ViewController: UIViewController {

    @IBOutlet weak var textFieldCopy: UITextField!
    @IBOutlet weak var textFieldPaste: UITextField!
    @IBOutlet weak var labelCopy: UILabel!
    @IBOutlet weak var labelPaste: UILabel!
    @IBOutlet weak var imageCopy: UIImageView!
    @IBOutlet weak var imagePaste: UIImageView!

    @IBAction func btnCopyStringAction(_ sender: Any) {
        
        UIPasteboard.general.string = textFieldCopy.text
        
    }
    
    
    @IBAction func btnPasteStringAction(_ sender: Any) {
        
        textFieldPaste.text = textFieldPaste.text! + UIPasteboard.general.string!
    }
    
    @IBAction func btnCopyUrlAction(_ sender: Any) {
        
        let oneHour = Date().addingTimeInterval(60 * 60)
        
        let pasteboard =  UIPasteboard.init(name: UIPasteboard.Name(rawValue: "sample_pasteboard"), create: true)
        pasteboard?.setItems([], options: [UIPasteboard.OptionsKey.localOnly : true, UIPasteboard.OptionsKey.expirationDate : oneHour])
        pasteboard?.setValue(URL(string: labelCopy!.text!) ?? "", forPasteboardType: kUTTypeURL as String)
    
    }
    
    @IBAction func btnPasteUrlAction(_ sender: Any) {
        
        let pasteboard = UIPasteboard.init(name: UIPasteboard.Name(rawValue: "sample_pasteboard"), create: true)
        labelPaste.text = pasteboard?.url?.absoluteString
    }
    
    @IBAction func btnCopyImageAction(_ sender: Any) {
        
        let image = imageCopy.image!
        if let data = image.pngData() {
            UIPasteboard.general.setData(data,forPasteboardType: kUTTypePNG as String)
        }
        
    }
    
    @IBAction func btnPasteImageAction(_ sender: Any) {
        
        
        let pasteboard = UIPasteboard.general
    
        let imageTypes = UIPasteboard.typeListImage as! [String]
        
        if pasteboard.contains(pasteboardTypes: imageTypes) {
            for imageType in imageTypes {
                if let data = pasteboard.data(forPasteboardType: imageType) {
                    if let pasteThisImage = UIImage(data: data) {
                        imagePaste.image = pasteThisImage
                        break
                    }
                }
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
}

We’ve imported MobileCoreServices which is used to set the types of the data.

我们已经导入了MobileCoreServices,用于设置数据类型。

In the Top StackView, we have two UITextField. We copy the string from one to the other.
In the Middle StackView, we copy the URL from a label to the other.

在顶部StackView中,我们有两个UITextField。 我们将字符串从一个复制到另一个。
在中间StackView中,我们将URL从标签复制到另一个标签。

To convert a string to a URL: 要将字符串转换为URL:

URL(string: String) URL(string: String)

Vice-versa:
URL.absoluteString

反之亦然:
URL.absoluteString

In the Middle StackView, we’ve created a named Pasteboard. The type of the value set is kUTTypeURL. We’ve set the expiry to an hour and set the Pasteboard as localOnly.

在中间StackView中,我们创建了一个名为Pasteboard。 值集的类型为kUTTypeURL 。 我们将有效期设置为一个小时,并将localOnly设置为localOnly

In the Bottom StackView, we copy an image by using pngData() to get the Data instance out of the image and set it in the setData() on the Pasteboard instance.
UIPasteboard.typeListImage is used to retrieve all the types of items in the Pasteboard.

在底部StackView中,我们使用pngData()复制图像以从图像中获取Data实例,然后在Pasteboard实例的setData()进行设置。
UIPasteboard.typeListImage用于检索UIPasteboard.typeListImage中所有类型的项目。

The output of the application in action is given below:

实际应用程序的输出如下:

This brings an end to this tutorial. You can download the project from the link below:

本教程到此结束。 您可以从下面的链接下载项目:

翻译自: https://www.journaldev.com/22723/ios-uipasteboard

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值