Copy Text with UIPasteBin

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

@interface ViewController ()

@property (nonatomic, weak) IBOutlet UITextField *fromTextField;
@property (nonatomic, weak) IBOutlet UITextField *toTextField;

- (IBAction)copyText:(id)sender;


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

@interface ViewController () <UITextFieldDelegate>

Change the viewDidLoad method to

- (void)viewDidLoad
[super viewDidLoad];

self.fromTextField.delegate = self;
self.toTextField.delegate = self;

Next, implement our textfield delegate method, textFieldShouldReturn

- (BOOL) textFieldShouldReturn:(UITextField *)textField
[textField resignFirstResponder];
return NO;

This method will dismiss the keyboard when the user enters the return key. All that's left is the implementation of our copyText method

- (IBAction)copyText:(id)sender {
NSString *copyString = self.fromTextField.text;
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
pasteBoard.string = copyString;

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.