LoginSignup
21
26

More than 5 years have passed since last update.

swiftでクリップボードにテキストを貼り付ける方法

Last updated at Posted at 2015-12-20

リリースしてるアプリの新機能でクリップボードに開いているWebページのリンクをコピーする機能をつけたくて、iOSアプリ内でのクリップボードの扱いについて初めて触れたので備忘として投稿しておく

すごく簡単だった・・・

結論から言うとものすごく簡単だった。
UIPasteboardというクラスが用意されており、そちらを利用すると下記の通り
これでCopy1というテキストがクリップボードに保持された。

@IBAction func tapCopy1Btn(sender: AnyObject) {
    let board = UIPasteboard.generalPasteboard()
    board.setValue("Copy1", forPasteboardType: "public.text")
}

generalPasteboardを使うと端末内で共有されるクリップボードに保持される。
Safariなりメモ帳なりでペーストするとCopy1が出力される

自身のアプリ内のみで使うものであれば

自身のアプリ内のみで利用したい場合はコチラ

@IBAction func tapCopy3Btn(sender: AnyObject) {
    let board = UIPasteboard(name: "Copy3", create: true)
    board!.setValue("Copy3", forPasteboardType: "public.text")
}

上記のようにUIPasteboardを名前指定して生成することができる。
で実際アプリ内でペーストする際は下記

@IBAction func tapPaste3(sender: AnyObject) {
    let board = UIPasteboard(name: "Copy3", create: true)
    sampleTextView.text.appendContentsOf((board?.string!)!)
}

画像をクリップボードに保持

上の例ではテキストはクリップボードに保持する処理を記述しているが、下記のようにすれば画像も保持することが可能

@IBAction func tapCopy2Btn(sender: AnyObject) {
    let board = UIPasteboard.generalPasteboard()
    board.setValue(UIImage(named: "sample_image")!, forPasteboardType: "public.image")
}
21
26
0

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
21
26