Tuesday, January 19, 2016

UIPasteboard - Copy text to clipboard / pasteboard

This post shows an example app with a button and a text view. By pressing the button, a string is copied to the clipboard/pasteboard. Then the string may be pasted into the text view by tapping and holding.

Modify ViewController.swift as below:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        let button : UIButton!
        button = UIButton(frame: CGRectMake(0, 0, 300, 30))
        button.center = CGPointMake(view.center.x, 100)
        button.setTitle("Copy String", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        button.addTarget(self, action: "btnPressed:", forControlEvents: UIControlEvents.TouchUpInside)
        let textView = UITextView(frame: CGRectMake(0, 0, 200, 100))
        textView.center = CGPointMake(view.center.x, 200)
        textView.backgroundColor = UIColor.cyanColor()
        textView.textColor = UIColor.blackColor()
        textView.textAlignment = NSTextAlignment.Center
    func btnPressed(sender: UIButton) {
        //Copy a string to the pasteboard.
        UIPasteboard.generalPasteboard().string = "The quick brown fox jumps over the lazy dog."
        let alertController = UIAlertController(title: "", message: "String copied to pasteboard!", preferredStyle: UIAlertControllerStyle.Alert)
        alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
        presentViewController(alertController, animated: true, completion: nil)

    override func didReceiveMemoryWarning() {



1 comment:

  1. It was so nice article. I was really satisfied by seeing this article. ios online course