如何在Swift中複製文字到剪貼簿?


在Swift中,有一個名為UIPasteboard的專用類,允許您將文字複製到貼上板。同一個類允許您貼上文字。

UIPasteboard類是UIKit框架的一部分,它為iOS應用程式中複製和貼上資訊提供了一個通用處理器。在這個類中,可以使用共享例項在應用程式之間複製和貼上資料。您可以共享各種型別的資訊,例如文字、媒體檔案、URL和顏色。

複製和貼上文字到剪貼簿

使用UIPasteboard類,您可以透過字串屬性在iOS應用程式中複製和貼上文字值。這是一個例子:

示例

import UIKit
let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
UIPasteboard.general.string = text

這會將文字字串複製到通用貼上板,其他應用程式可以訪問該貼上板。

為了從貼上板貼上文字,您可以像這樣檢索它:

import UIKit
let text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
UIPasteboard.general.string = text
if let pastedText = UIPasteboard.general.string {
   print("Pasted text: \(pastedText)")
}

輸出

Pasted text: Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

此字串屬性為您提供通用貼上板中當前的文字(如果存在),這就是它返回可選字串值的原因。

複製和貼上URL到剪貼簿

使用UIPasteboard類,您可以透過“url”屬性在iOS應用程式中複製和貼上URL表示。這是一個例子:

示例

let urlObject = URL(string: "https://tutorialspoint.tw/")
UIPasteboard.general.url = urlObject
if let pastedObject = UIPasteboard.general.url {
   print("Pasted value: \(pastedObject)")
}

輸出

Pasted value: https://tutorialspoint.tw/

注意 - 從iOS 14開始,當應用程式獲取源自不同應用程式的通用貼上板內容而無需使用者意圖時,系統會通知使用者。系統根據使用者互動(例如點選系統提供的控制元件或按Command-V)來確定使用者意圖。使用下面的屬性和方法來確定貼上板專案是否與各種模式匹配,例如網路搜尋詞、URL或數字,而無需通知使用者。

結論

透過使用UIPasteboard的共享例項,您可以共享文字、影像、URL和其他型別的資訊。在這個類中有一個名為“general”的共享例項,用於執行所有通用的複製和貼上操作。

更新於:2023年4月4日

3K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.