[Tutorial] Copy Text using UIPasteBoard

A useful feature to have in your iOS Apps is to give the user the ability to be able to copy content within your App. Whether it be text or images, you can copy most content. To do this, we need to use the UIPasteBoard feature of the iPhone SDK. In this tutorial we will have a UILabel, a UIButton and a UITextField. The label will hold the text to be copied, the button will fire the code to copy the text and then you will be able to paste the text into the textfield.

Step 1: Write the .h

First off in the ViewController.h we need in declare IBAction’s for our UILabel and UITextField, I named mine ‘label’ and ‘textField’ respectively. Next we need to create an IBAction for our button that will fire the code to copy the text. That’s it for the .h!

h

Step 2: Write the .m

Inside our IBAction in the .m, we want to set up the code that will copy the text from the UILabel into the UITextField. First off we create an NSString that holds the text of our label. On the next line, we set up the UIPasteBoard, I named mine ‘pb’, but you can name it anything you want. Next we set the text to be copied by the UIPasteBoard to be the NSString we set up earlier which is holding the text of our label.

That’s the coding part done!

m

Step 3: Hook things up in Interface Builder

Now we need to set up the interface. To do that we’re going to use interface builder. Open up Interface Builder and drag a UILabel, UIButton and UITextField from the Library onto our view. Set the text of the label to be the text you want to be copied, set the title of the button to be ‘Copy Text’ and leave the textfield blank. Then click on ‘Files Owner’ and in the Inspectors sidebar select the ‘Connections’ tab. Then drag the received action ‘copy’, onto our button. Select Touch Up Inside. Then we need to hook up our label and textfield. So under ‘Outlets’ drag ‘label’ to the UILabel and ‘textField’ to the UITextField.

We’re done!

IB

Step 5: Build and Run!

Now we can build the project and copy text using UIPasteBoard!

Simulator1Simulator

Download the Sample Project

Xcode

Download the Xcode Project here: UIPasteBoard

I hope you find this tutorial useful. If you have any questions or improvements, please email me using the Contact Page or Tweet me @JASApplications