Tutorials

In iOS a user has the ability to copy/paste text from different sources of text. To make use of this feature inside an app, we can use the UIPasteBin object. In this tutorial we copy/paste some text from/to TextFields.

Update: Nov 24, 2014. The rewritten version in Swift for iOS 8 and Xcode 6 is available here.

Open Xcode and create a new Single View Application. For product name, use CopyTextDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.

First, Let's create our User Interface. Go to ViewController.xib. Drag 2 TextFields and a Button to the main View. The main View should look like this.

In ViewController.m in the interface section declare the following properties and IBAction method

Go back to ViewController.xib. Select the Assistant Editor. On the right side select ViewController.m. Ctrl-click and drag from the top TextField to the IBOutlet fromTextField in ViewController.m. Ctrl-click and drag from the bottom TextField to the IBOutlet toTextField.Next, Ctrl-click and drag from the Copy button to the @implementation copyText method.

When the user clicks the TextField the keyboard is presented. To dismiss the keyboard our ViewController must conform to the UITextFieldDelegate protocol. Change the @interface line in

The text from the fromTextField is copied over to the pasteboard, where we can paste it from.
Build and Run, Enter some text in the top Textfield, press the copy button and paste the text back in the bottom button.

You can download the source code of the CopyTextDemo at the ioscreator repository on github.