LoginSignup
5

【Swift】クリップボードに文字列や画像をコピーする

Last updated at Posted at 2021-11-06

SwiftでiOSアプリを開発する際に、クリップボードに文字列をコピーするコード。

クリップボードに文字列をコピー

文字列をコピーする時のコードは以下の通り。

let str = "コピーしたい文字列"
UIPasteboard.general.string = str

クリップボードに画像をコピー

画像も同様にコピー可能です。

//1枚の画像をコピー
let img = UIImage(named: "sample")
UIPasteboard.general.image = img

//複数の画像をコピー
let img1 = UIImage(named: "sample1")
let img2 = UIImage(named: "sample2")
UIPasteboard.general.images = [img1!,img2!]

他にコピーできる種類

文字列や画像以外もURLや色のコピー可能です。

var url: URL?
The URL object of the first pasteboard item.

var urls: [URL]?
An array of URL objects in all pasteboard items.

var color: UIColor?
The color object of the first pasteboard item.

var colors: [UIColor]?
An array of color objects in all pasteboard items.

https://developer.apple.com/documentation/uikit/uipasteboard

参考

おすすめ情報

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5