-2

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.

Squared
  • 308
  • 3
  • 13
  • 1
    What have you done so far and what doesn't work exactly? – mag_zbc Jun 19 '19 at 09:55
  • so far I have added a label to ViewController, that' it. – Squared Jun 19 '19 at 09:57
  • If it's not suitable to use a `UIButton` instead, you will also need to consider a [Gesture Recogniser](https://developer.apple.com/documentation/uikit/uigesturerecognizer) – Wez Jun 19 '19 at 09:57

4 Answers4

5

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

Thierry N.
  • 66
  • 1
  • 2
3

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

}

}

Squared
  • 308
  • 3
  • 13
1

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?

ojassethi
  • 379
  • 1
  • 5
  • 16
1

For copying text to your clipBoard.

 UIPasteboard.general.string = yourLabel.text
Awais Khan
  • 116
  • 9