Swift - UIPasteboard剪贴板的使用详解(复制、粘贴文字和图片)
转载自:http://www.hangge.com/blog/cache/detail_1085.html
UITextField、UITextView组件系统原生就支持文字的复制,但有时我们需要让其他的一些组件也能实现复制功能,比如点击复制UILabel上的文字、UIImageView中的图片、UITableView里单元格的内容、或者点击按钮把文字或图片自动复制到粘贴板中等等。
|
1
|
UIPasteboard.generalPasteboard().string = "欢迎访问 hangge.com" |
2,复制字符串数组
|
1
|
UIPasteboard.generalPasteboard().strings = ["hellow", "hangge.com"] |
3,复制图片
|
1
2
|
let image = UIImage(named: "logo.png")UIPasteboard.generalPasteboard().image = image |
4,复制二进制数据(NSData)
|
1
2
3
|
let path = NSBundle.mainBundle().pathForResource("logo", ofType: "png")!let fileData = NSData(contentsOfFile: path)!UIPasteboard.generalPasteboard().setData(fileData, forPasteboardType: "public.png") |
注:从剪贴板获取二进制数据(NSData)
|
1
|
let myData = UIPasteboard.generalPasteboard().dataForPasteboardType("public.png") |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
import UIKitclass UICopyLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) sharedInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedInit() } func sharedInit() { userInteractionEnabled = true addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "showMenu:")) } func showMenu(sender: AnyObject?) { becomeFirstResponder() let menu = UIMenuController.sharedMenuController() if !menu.menuVisible { menu.setTargetRect(bounds, inView: self) menu.setMenuVisible(true, animated: true) } } //复制 override func copy(sender: AnyObject?) { let board = UIPasteboard.generalPasteboard() board.string = text let menu = UIMenuController.sharedMenuController() menu.setMenuVisible(false, animated: true) } override func canBecomeFirstResponder() -> Bool { return true } override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if action == "copy:" { return true } return false }} |
在这个文本标签上长按后便可以复制其内容:

我们自定义一个图片控件类 UICPImageView(继承UIImageView),内部同样添加Touch事件响应。该控件不仅支持复制,还支持粘贴。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
import UIKitclass UICPImageView: UIImageView { override init(frame: CGRect) { super.init(frame: frame) sharedInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) sharedInit() } func sharedInit() { userInteractionEnabled = true addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: "showMenu:")) } func showMenu(sender: AnyObject?) { becomeFirstResponder() let menu = UIMenuController.sharedMenuController() if !menu.menuVisible { menu.setTargetRect(bounds, inView: self) menu.setMenuVisible(true, animated: true) } } //复制 override func copy(sender: AnyObject?) { let board = UIPasteboard.generalPasteboard() board.image = self.image let menu = UIMenuController.sharedMenuController() menu.setMenuVisible(false, animated: true) } //粘贴 override func paste(sender: AnyObject?) { let board = UIPasteboard.generalPasteboard() self.image = board.image let menu = UIMenuController.sharedMenuController() menu.setMenuVisible(false, animated: true) } override func canBecomeFirstResponder() -> Bool { return true } override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if action == "copy:" { return true }else if action == "paste:" { return true } return false }} |
下面我们在界面上添加两个 UICPImageView,我们可以把左边控件里的图片复制到右边控件中来,效果图如下:

3,让表格(UITableView)支持复制功能
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
import UIKitclass ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var tableView:UITableView? var tableData = ["条目1", "条目2", "条目3", "条目4", "条目5", "条目6", "条目7"] override func loadView() { super.loadView() } override func viewDidLoad() { super.viewDidLoad() //创建表视图 self.tableView = UITableView(frame: self.view.frame, style:.Plain) self.tableView!.delegate = self self.tableView!.dataSource = self //创建一个重用的单元格 self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "SwiftCell") self.view.addSubview(self.tableView!) } func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { let board = UIPasteboard.generalPasteboard() board.string = tableData[indexPath.row] } func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { if action == "copy:" { return true } return false } func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } //在本例中,只有一个分区 func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } //返回表格行数(也就是返回控件数) func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } //创建各单元显示内容(创建参数indexPath指定的单元) func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //为了提供表格显示性能,已创建完成的单元需重复使用 let identify:String = "SwiftCell" //同一形式的单元格重复使用,在声明时已注册 let cell = tableView.dequeueReusableCellWithIdentifier(identify, forIndexPath: indexPath) as UITableViewCell cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.textLabel?.text = tableData[indexPath.row] return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() }} |
长按某个单元格即可复制这个单元格内容:

原文出自:www.hangge.com 转载请保留原文链接:http://www.hangge.com/blog/cache/detail_1085.html
Swift - UIPasteboard剪贴板的使用详解(复制、粘贴文字和图片)的更多相关文章
- Swift 中的Closures(闭包)详解
Swift 中的Closures(闭包)详解 在Swift没有发布之前,所有人使用OC语言编写Cocoa上的程序,而其中经常被人们讨论的其中之一 -- Block 一直备受大家的喜爱.在Swift中, ...
- 重新想象 Windows 8 Store Apps (40) - 剪切板: 复制/粘贴文本, html, 图片, 文件
[源码下载] 重新想象 Windows 8 Store Apps (40) - 剪切板: 复制/粘贴文本, html, 图片, 文件 作者:webabcd 介绍重新想象 Windows 8 Store ...
- vmware12中ubuntu16.10的vmware tools失效,导致不能复制粘贴文字以及自动适应窗口分辨率
问题: 复制命令后,在vmware的ubuntu中粘贴不了,网上说要安装VMWare Tools,但是安装了VMWare Tools 还是不行! 最终找到如下方法: 新安装或异常关机和重新划分分区导致 ...
- 前端复制粘贴文字clipBoard.js的使用
1. vue 中的复制粘贴: <div class="mainTextItem" @click="copyTXTOne" id="copyOn ...
- 【iOS】Swift ?和 !(详解)
Swift语言使用var定义变量,但和别的语言不同,Swift里不会自动给变量赋初始值, 也就是说变量不会有默认值,所以要求使用变量之前必须要对其初始化 .如果在使用变量之前不进行初始化就会报错: [ ...
- [Swift实际操作]八、实用进阶-(9)Swift中的链表LinkedList详解
链表是一种物理存储单元上的非连续.非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针连接次序实现的.相比于线性表的顺序结构,链表比较方便插入和删除操作.本文将讲解如何模拟一个链表. //链表的节点 ...
- pandas常用操作详解(复制别人的)——数据透视表操作:pivot_table()
原文链接:https://www.cnblogs.com/Yanjy-OnlyOne/p/11195621.html 一文看懂pandas的透视表pivot_table 一.概述 1.1 什么是透视表 ...
- Ditto —— windows 剪贴板增强小工具(复制粘贴多条记录)
Windows 虽然不断在升级,但系统自带的剪贴板功能却仍然弱爆了 (只能保留一条记录). Ditto 下载地址:http://sourceforge.net/projects/ditto-cp/fi ...
- cocos2d-x 详解之 CCTexture2D(纹理图片)和 CCTextureCache(纹理缓存)
精灵和动画都涉及到纹理图片的使用,所以在研究精灵与动画之前,我们先来了解一下纹理图片类CCTexture2D和纹理缓存CCTextureCache的原理: 当一张图片被加载到内存后,它是以纹理的形式存 ...
随机推荐
- [POJ] String Matching
String Matching Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 4074 Accepted: 2077 D ...
- HDU 1069 I Think I Need a Houseboat(模拟)
题目链接 Problem Description Fred Mapper is considering purchasing some land in Louisiana to build his h ...
- gcc-config: Active gcc profile is invalid解决办法
错误描述 Gentoo软件安装错误,提示: gcc-config: Active gcc profile is invalid 解决方法: 列出可用的profile gcc-config -l gcc ...
- 第四题 (List)写一个函数reverseList,该函数能够接受一个List,然后把该List 倒序排列。 例如: List list = new ArrayList(); list.add(“Hello”); list.add(“World”); list.add(“Learn”); //此时list 为Hello World Learn r
package zuoye; import java.util.ArrayList; import java.util.List; public class Reverse01 { public st ...
- 将json文件转换为字符串
//从给定位置读取Json文件 public String readJson(String path){ //从给定位置获取文件 File file = new ...
- SQL STUFF函数 拼接字符串
今日看到一篇文章,是关于和并列的,也研究了下,还是不错的 要这种效果. create table tb(idint, value varchar(10)) insert into tbvalues(1 ...
- html5--基础笔记
1.对于<a>标签 以前: <h2><a href="index.html">The home page</a></h2> ...
- webstrom官方的活动模版介绍
编辑模板变量对话框 文件|设置|生活模板--编辑变量Windows和LinuxWebStorm |偏好|生活模板--编辑变量在OS XCtrl + Alt + S 当你点击对话框打开 编辑变量按钮模板 ...
- android 进程(复习)
前台进程 前台进程是用户当前正在使用的进程.只有一些前台进程可以在任何时候都存在.他们是最后一个被结束的,当内存低到根本连他们都不能运行的时候.一般来说, 在这种情况下,设备会进行内存调度,中 ...
- js键盘键值大全
原文地址:http://blog.csdn.net/avenccssddnn/article/details/7950524 js键盘键值 keycode 8 = BackSpace BackSpac ...