使用IOS通用粘帖板

倖福魔咒の 提交于 2019-12-03 21:31:02
使用通用粘帖板
generalPasteboard类方法返回一个通用粘帖板的指针,例如:
  UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
常用属性
 
最常用的粘帖板操作包括获取/设置字符串,图像,URL和颜色。Apple提供了以下方便的方法:

NSString *string = pasteboard.string;  
UIImage *image = pasteboard.image;  
NSURL *url = pasteboard.URL;  
UIColor *color = pasteboard.color;    
pasteboard.string = @"paste me somewhere";
 
确定一种类型的表示是否存在
 
如果某种类型的条目不存在,那么getter方法将返回nil。这是一个很方便的方法可以预先知道特定类型的表示是否存在。使用containsPasteboardTypes: 方法检查:
1
2
if ([pasteboard containsPasteboardTypes: [NSArray arrayWithObject:@"public.utf8-plain-text"]])      
    NSLog(@"String representation present: %@", pasteboard.string);
 
使用pasteboardTypes可获取一个条目的各种类型。
 
统一类型标志符 — UTI
 
上例中通过检查public.utf8-plain-text类型来确定字符串是否存在。本例将使用UTI(通用类型标志符)。有关UTI信息,请见Apple的 通用类型标志符概述文档。
 
Apple在UTCoreTypes.h中提供了通用类型的常量。要使用这些常量:
在项目中加入MobileCoreServices framework
#import
 
常量的类型是CFStringRef。你可以把它们当作NSString。CFStringRef是一种C和Objective-C通用的表达方式。为在Objective-C使用它,只需简单的转换操作:
1
NSString *urlUTIType = (NSString *)kUTTypeURL;
 
你可以自由构造自己的数据类型;为保证独特性,Apple推荐使用reverse-DNS标记式样(如com.mobileorchard.mySnazzyType)。
 
设置/提取缺乏Getter/Setter的类型
 
Getter/Setter只是为了提供方便。实际上,它们与使用valueForPasteboardType: 和 setValue:forPasteboardType 方法没什么区别:

NSString *string = [pasteboard valueForPasteboardType:@"public.utf8-plain-text"];  
[pasteBoard setValue:@"paste me somewhere" forPasteboardType:@"public.utf8-plain-text"];
 
此方法适用于字符串,数组,字典,日期,数值和URL。而dataForPasteboardType 和 setData:forPasteboardType: 方法适用于其它各种类型。
 
以多种表示存储条目
 
使用方便的setter有一个很大的限制:条目只能以一种类型存储。而如果使用上述方法,我们可以将URL存为NSString和NSURL,以构成一个类型和值的字典并设置其条目属性:

static NSString *string = @"http://www.mobileorchard.com";  
NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys: string,

    @"public.utf8-plain-text", [NSURL URLWithString:string],    
    (NSString *)kUTTypeURL,     nil];  
pasteboard.items = [NSArray arrayWithObject:item];
 
现在,pasteboard.string和pasteboard.url都将有内容返回了。
 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!