使用UIPasteboard在iOS中实现复制功能

48
 NSString *copyStringverse = [[NSString alloc] initWithFormat:@"%@",[textview.text]];
 UIPasteboard *pb = [UIPasteboard generalPasteboard];
 [pb setString:copyStringverse];

我正在使用上面的代码来复制 textview 中的内容,但我想要复制表格中单元格的内容。如何做到这一点?


2
这为我提供了完美的解决方案,可以从我的应用程序中复制/粘贴 - 无论您需要略微不同的内容。干杯! - Dan Hanly
5个回答

72

你没有明确说明你的表格视图单元格是如何设置的,但如果它只是表格视图中的文本,那么可能很容易:

// provided you actually have your table view cell
NSString *copyStringverse = yourSelectedOrClickedTableViewCell.textLabel.text;
UIPasteboard *pb = [UIPasteboard generalPasteboard];
[pb setString:copyStringverse];

嗨,谢谢你的回复。你选中或点击的单元格是哪一个?表名是什么? - stackiphone
@Micheal Dautermann 我需要将它放在按钮点击事件内,这样文本标签才会显示错误。 - stackiphone
yourSelectedOrClickedTableViewCell 是一个 UITableViewCell。你需要找出哪个单元格被点击了。我不知道你的代码的其余部分是什么样子的,所以我不知道你将如何调用复制操作,也无法提供更好的代码示例。 - Michael Dautermann

27
[UIPasteboard generalPasteboard].string = @"Copy me!";

15

对于 Swift 3.x

UIPasteboard.general.string = "String to copy"

4

针对Swift 2.1+版本:

let cell = tableView.cellForRowAtIndexPath(indexPath) as! UITableViewCell // change this to your custom cell if you use one
UIPasteboard.generalPasteboard().string = cell.textLabel.text

1

对于 Swift2.2

UIPasteboard.generalPasteboard().string = tableViewCell.textLabel.text

通过使用此方法,您可以直接将值设置到 UIPasteboard 中。

请注意,在Swift 3中,“generalPasteboard()”不再存在。请使用“general”代替。 - PeterPan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接