PasteBoard Tutorial in iOS8 with Swift

In iOS8  the user has the ability to copy and paste text from different sources.. To make use of this feature inside an app, we can use the UIPasteBin object. In this tutorial we copy some text from a Text Field and paste it to a Text Field. This Tutorial is built with iOS 8.1 and Xcode 6.1.

Open Xcode and create a new Single View Application. For product name, use IOS8SwiftPasteBinTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to The StoryBoard and Add Two Text Fields and a button to the Storyboard. Give the button a title of "Copy". Select all three items and choose the "Resolve Auto Layout Button". (3rd button in the bottom-right corner) and select "Add Missing Constraints".

Give the main View a light-gray background.The Storyboard should look like this.

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the first Text Field to the ViewController class  and create the following Outlet.

Repeat this step for the second Text Field.

Ctrl and drag from the Button to the View Controller class and create the following Action

When the user clicks the Text Field the keyboard is presented. To dismiss the keyboard our ViewController must conform to the UITextFieldDelegate protocol. Change the class declaration line to

class ViewController: UIViewController, UITextFieldDelegate {

hange the viewDidLoad method to

override func viewDidLoad() {
    fromTextField.delegate = self
    toTextField.delegate = self

The View Controller is the delegate of the UITextFieldDeleGate. We need to implement the textFieldShouldReturn method

func textFieldShouldReturn(textField: UITextField) -> Bool {
    return false

When the Return key is pressed the Keyboard is dismissed. Next, implement the copyText method

@IBAction func copyText(sender: AnyObject) {
    var copyString = fromTextField.text
    var pasteBoard = UIPasteboard.generalPasteboard()
    pasteBoard.string = copyString

The text from the First Textfield is assigned to a String. Next, a UIPasteBoard object is initialised with a general PasteBoard. The text from the string is then assigned to the string property of the UIPasteBoard class. Build and Run the project, enter some text in the first Text Field, select Copy and then paste it into the second Text Field.

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