简体   繁体   English

如何使用 Swift 以编程方式粘贴?

[英]How do I paste programmatically with Swift?

I want to have a button the user can press that will automatically paste whatever text is in the clipboard into a UITextView .我想要一个用户可以按下的按钮,它会自动将剪贴板中的任何文本粘贴到UITextView

How can I do that in Swift?我怎样才能在 Swift 中做到这一点?

It has been answered here but it's in Objective-C.它已在此处得到解答但它在 Objective-C 中。

You should just be able to convert those to Swift:您应该能够将它们转换为 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
}

You can implement copy and paste method in Swift like:您可以在 Swift 中实现复制和粘贴方法,例如:

// 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!;
}

For Swift 5.0 and up对于Swift 5.0及更高版本

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM