-1

first I have to make UILabel clickable and when it clicked it should copy its text to clipboard. I am using Xcode 10 with swift 5.1.

so firstly I am expecting label to be clickable and after that, this click action copy its text to clipboard. this is a basic level program.

3
  • 1
    What have you done so far and what doesn't work exactly?
    – mag_zbc
    Jun 19, 2019 at 9:55
  • so far I have added a label to ViewController, that' it.
    – Squared
    Jun 19, 2019 at 9:57
  • If it's not suitable to use a UIButton instead, you will also need to consider a Gesture Recogniser
    – Wez
    Jun 19, 2019 at 9:57

4 Answers 4

6

To make the label "clickable" :

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(labelDidGetTapped:))

yourLabel.userInteractionEnabled = true
yourLabel.addGestureRecognizer(tapGesture)

Then, to retrieve the text from the label and copy it to the clipboard :

@objc
func labelDidGetTapped(sender: UITapGestureRecognizer) {
    guard let label = sender.view as? UILabel else {
        return
    }
    UIPasteboard.general.string = label.text
}

Note that there won't be any effect when tapping the text, it would be best to present some kind of feedback to the user, by animating the label's alpha for example

4

Part one of the answer can be followed as -

    @IBOutlet weak var clickAble: UILabel!

    override func viewDidLoad() {
    super.viewDidLoad()

    // this code is for making label clickable.
    clickAble.isUserInteractionEnabled = true
    let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapFunction))
    tap.numberOfTapsRequired = 1
    clickAble.addGestureRecognizer(tap)

}

Part 2nd of answer is as-

@objc func tapFunction(sender:UITapGestureRecognizer)
{
    // this is for copying label text to clipboard.
    let labeltext = clickAble.text
    UIPasteboard.general.string = labeltext

}

}

2

Try making user interaction enabled. For example:

yourLabel.isUserInteractionEnabled = true

Check this previous thread. This question has already been answered. How to make a UILabel clickable?

1

For copying text to your clipBoard.

 UIPasteboard.general.string = yourLabel.text

Not the answer you're looking for? Browse other questions tagged or ask your own question.