Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I paste programmatically with Swift?

Tags:

ios

swift

paste

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.

like image 940
webmagnets Avatar asked Dec 27 '14 04:12

webmagnets


2 Answers

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
}
like image 100
AstroCB Avatar answered Oct 14 '22 19:10

AstroCB


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!;
}
like image 32
Midhun MP Avatar answered Oct 14 '22 19:10

Midhun MP