How to do copy/paste function programmatically in

2019-01-30 11:25发布

I have a text-view with some text and a copy button in that view,

When the user enters some text and presses the copy button, it needs to copy that text and paste that text wherever he wants.

I know there is a default copy/paste menu-controller in iOS, but I want to do this functionality in a button click. I think there is UIPasteboard to do this functionality, but I don't know how to use it.

5条回答
劳资没心,怎么记你
2楼-- · 2019-01-30 11:38

Swift

This is the Swift version of the accepted answer.

Copy

UIPasteboard.general.string = myTextView.text

Paste

if let myString = UIPasteboard.general.string {
    myTextView.insertText(myString)
}
查看更多
戒情不戒烟
3楼-- · 2019-01-30 11:40

For developers using MonoTouch, here are the two lines I used to complete the task in C#.

The answer iscavenger provided to this question served as the model for my answer (after I successfully implemented it in my project ;-)

UIPasteboard clipboard = UIPasteboard.General;
clipboard.String =  "string being added to clipboard";
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-30 11:40

I suspect you can relatively easily do what you want, starting with the [UIPasteboard dataForPasteboardType:] method.

There's Apple sample code you can look into at:

http://developer.apple.com/library/ios/#samplecode/CopyPasteTile/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009040

查看更多
孤傲高冷的网名
5楼-- · 2019-01-30 11:41

Not sure why we can't simply use:

[theTextView paste:nil];

as per UIResponder docs

查看更多
老娘就宠你
6楼-- · 2019-01-30 11:42

To copy from a button click:

- (IBAction)copy {
    UIPasteboard *pb = [UIPasteboard generalPasteboard];
    [pb setString:[textView text]];
}

To paste from a button click:

- (IBAction)paste {
    UIPasteboard *pb = [UIPasteboard generalPasteboard];
    textView.text = [pb string];
}
查看更多
登录 后发表回答