PasteBoard iOS Tutorial

In iOS the user has the ability to copy and paste text from different sources. To make use of this feature inside an app, the UIPasteBin object can be used. In this tutorial some text will be copied from a Text Field and paste it to an other Text Field. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSPasteBinTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to The StoryBoard and Add Two Text Fields and a button to the Storyboard. Give the button a title of "Copy". Select the "Resolve Auto Layout Button the bottom-right corner of Interface Builder and select "Reset to Suggested 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 {

Change 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: Any) {
    let copyString = fromTextField.text
    let pasteBoard = UIPasteboard.general
    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 IOSPasteBinTutorial at the ioscreator repository on github.