10

I want to have a button the user can press that will automatically paste whatever text is in the clipboard into a UITextView.

How can I do that in Swift?

It has been answered here but it's in Objective-C.

Community
  • 1
  • 1
webmagnets
  • 2,266
  • 3
  • 33
  • 60

4 Answers4

20

You should just be able to convert those to Swift:

@IBAction func copy() {
    let pb: UIPasteboard = UIPasteboard.generalPasteboard();
    pb.string = textView.text // Or another source of text
}

@IBAction func paste() {
    let pb: UIPasteboard = UIPasteboard.generalPasteboard();
    textView.text /*(Or somewhere to put the text)*/ = pb.string
}
AstroCB
  • 12,337
  • 20
  • 57
  • 73
4

You can implement copy and paste method in Swift like:

// Function receives the text as argument for copying
func copyText(textToCopy : NSString)
{
    let pasteBoard    = UIPasteboard.generalPasteboard();
    pasteBoard.string = textToCopy; // Set your text here
}

// Function returns the copied string
func pasteText() -> NSString
{
    let pasteBoard    = UIPasteboard.generalPasteboard();
    println("Copied Text : \(pasteBoard.string)"); // It prints the copied text
    return pasteBoard.string!;
}
AstroCB
  • 12,337
  • 20
  • 57
  • 73
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
1

For Swift 5.0 and up

func copyText(from text: String) {
    weak var pb: UIPasteboard? = .general
    pb?.string = text
}

func pasteText() -> String? {
    weak var pb: UIPasteboard? = .general
    
    guard let text = pb?.string else { return nil}
    
    return text
}
Pramodya Abeysinghe
  • 1,098
  • 17
  • 13
-1

Simplest Way - Swift 5+

Easy way to add any standard Swift type, is using the setter:

UIPasteboard.general.string = "Pasted String"
Sverrisson
  • 17,970
  • 5
  • 66
  • 62