LoginSignup
5
4

More than 5 years have passed since last update.

【Swift4】タップでラベルのテキストをクリップボードへ【iOS】

Last updated at Posted at 2017-12-18

不可視ボタンを乗せたり、touchesEndedをオーバーライドする手もありますが、タップジェスチャーがおすすめです。
 

不可視ボタン => ラベルオブジェクトのサイズが可変な場合は制約を同じにする必要がある
touchesEnded => タップされたオブジェクトの判別ロジックが必要

コードから

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tapLabel:UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        tapLabel.text = "please tap here"
        tapLabel.isUserInteractionEnabled = true

        let tg = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedLabel(_:)))
        tapLabel.addGestureRecognizer(tg)
    }

    @objc func tappedLabel(_ sender:UITapGestureRecognizer) {
        UIPasteboard.general.string = tapLabel.text
        print("clip board :\(UIPasteboard.general.string!)")
    }

}

ストーリーボードで

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tapLabel:UILabel!
    @IBAction func tapAction(_ sender: UITapGestureRecognizer) {
        UIPasteboard.general.string = tapLabel.text
        print("clip board :\(UIPasteboard.general.string!)")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tapLabel.text = "please tap here"
        tapLabel.isUserInteractionEnabled = true
    }  
}  

 

テキストを扱う場合、setValue()ではなく、stringプロパティを使うこと
// iOS11では動作しない
UIPasteboard.general.setValue("source string", forPasteboardType: "public.text")

// これならOK
UIPasteboard.general.string = "source string"
5
4
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
5
4