1,复制粘贴字符串
//这个是需要输入的信息,即是要复制的信息
UITextField *textfild = [[UITextField alloc] init];
self.textfild = textfild;
textfild.placeholder = @"请输入信息";
textfild.font = [UIFont systemFontOfSize:17];
[textfild setTextColor:[UIColor redColor]];
textfild.frame = CGRectMake(10, 60, [UIScreen mainScreen].bounds.size.width-20, 40);
textfild.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textfild];
//把上面复制的信息粘贴到这个控件中,用
UITextField *textfild2 = [[UITextField alloc] init];
self.textfild2 = textfild2;
textfild2.placeholder = @"请输入信息2";
textfild2.font = [UIFont systemFontOfSize:17];
[textfild2 setTextColor:[UIColor redColor]];
textfild2.frame = CGRectMake(10, CGRectGetMaxY(textfild.frame)+10, [UIScreen mainScreen].bounds.size.width-20, 40);
textfild2.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:textfild2];
执行下面的方法会把textfild中的信息粘贴给textfild2
/**
共享的字符串
*/
- (void)shareNSString{
//把信息放入粘贴板中
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
self.pasteboard = pasteboard;
pasteboard.string = self.textfild.text;
// pasteboard.strings = @[self.textfild.text,@"haha"];
//从粘贴板中取出数据
NSString *str = [UIPasteboard generalPasteboard].string;
// NSArray *ar = pasteboard.strings;
// NSString *str = [NSString stringWithFormat:@"%@,%@",ar[0],ar[1]];
self.textfild2.text = str;
}
2,复制粘贴图片
//要被复制的图片
UIImageView *imageview1 = [[UIImageView alloc] init];
self.imageview1 = imageview1;
imageview1.frame = CGRectMake(10, CGRectGetMaxY(textfild2.frame)+10, 100, 100);
imageview1.contentMode = UIViewContentModeScaleAspectFill;
imageview1.clipsToBounds = YES;
imageview1.image = [UIImage imageNamed:@"wuyifan"];
[self.view addSubview:imageview1];
//粘贴照片
UIImageView *imageview2 = [[UIImageView alloc] init];
self.imageview2 = imageview2;
imageview2.frame = CGRectMake(10, CGRectGetMaxY(imageview1.frame)+20, 100, 100);
imageview2.contentMode = UIViewContentModeScaleAspectFill;
imageview2.clipsToBounds = YES;
[self.view addSubview:imageview2];
执行下面的方法把复制的图片粘贴到imageview2上
/**
共享data数据
*/
- (void)shareData{
//把信息放入粘贴板
UIPasteboard *pastedboard = [UIPasteboard generalPasteboard];
NSData *data = UIImageJPEGRepresentation(self.imageview1.image, 1.0);
[pastedboard setData:data forPasteboardType:@"imagedata"];
//从粘贴板中取出数据
NSData *data2 = [pastedboard dataForPasteboardType:@"imagedata"];
UIImage *image2 = [UIImage imageWithData:data2];
self.imageview2.image = image2;
}
3,剪贴板和 URL Scheme之间的比较
剪贴板:它具有支持复杂数据(如图片)的能力;支持多种形式表示数据;在应用关闭后,剪贴板内容仍然会被保留。
与URL Scheme比较,它不能够判断是否安装了目标app;任何应用都可以访问剪贴板,会带来安全问题;
剪贴板不仅消耗内存,也需要额外的时间来读写,程序进入后台等状态时,应当清除剪贴板,pastedboard.items = nil;