iOS开发-剪切板实现拷贝粘贴

简单介绍

在应用程序中,经常会有对一段文字进行拷贝、剪切、粘贴的需求,iOS提供了3个自带这些功能的控件:

  • UITextField
  • UITextView
  • UIWebView

但是实际中有时候可能需要对这3个以外的控件进行文本、图片等的拷贝粘贴,就需要自定义实现。UIKit framework为我们提供了几个相关的类和协议用来实现这一功能。

  1. UIPasteboard:剪切板,用来向其中写入数据以及从中读取数据,从来实现数据的”搬迁”。
  2. UIMenuController:编辑菜单,用来显示拷贝、黏贴等命令
  3. canPerformAction:withSender::用于控制编辑菜单显示的命令按钮。事实上,编辑菜单的命令按钮完全可以自定义,而无需通过实现canPerformAction:方法来控制命令按钮。
  4. UIResponderStandardEditActions:一个非正式协议(UIResponder的类别),申明了几个编辑动作,例如copy:等等。当编辑菜单上的命令被点击时,相关方法会被调用。系统未实现这个方法,必须override!

剪切板类型

系统级:其中的数据可以在任意app之间共享。包括UIPasteboardNameGeneral和UIPasteboardNameFind,这种剪切板不管是应用程序终止、卸载还是关机重启,数据都不会丢失。

应用程序级:数据只能在具有相同 team ID 的app之间共享。可以通过persistent属性设置成app退出以及系统重启数据都不丢失,但是app被卸载后数据就没了。

实例

UILabel文本拷贝

创建一个自定义标签类(继承自UILabel),实现文件中添加如下代码:

@implementation MyLabel

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(actionShowMenu:)];
        [self addGestureRecognizer:longPressGestureRecognizer];
    }
    return self;
}

- (void)actionShowMenu:(UILongPressGestureRecognizer *)recoginzer{
    if (recoginzer.state == UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];  //成为第一响应
        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setTargetRect:CGRectMake([recoginzer locationInView:self].x, [recoginzer locationInView:self].y, 0, 0) inView:self]; //设置menu显示位置
        [menu setMenuVisible:YES animated:YES];  //显示menu
    }
}

/*!
 *  允许成为第一响应
 */
- (BOOL)canBecomeFirstResponder{
    return YES;
}

/*!
 *  用于控制哪些命令显示在编辑菜单中
 */
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    if (action == @selector(copy:)) {
        return YES;
    }
    return NO;
}

- (void)copy:(id)sender{
    [UIPasteboard generalPasteboard].string = self.text;
}

@end

演示效果如下:

UIImageView实现图片的拷贝

创建一个自定义图像视图类(继承自UIImageView),实现文件中添加如下代码:

@implementation MyImageView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(actionShowMenu:)];
        [self addGestureRecognizer:longPressGestureRecognizer];
    }
    return self;
}

- (void)actionShowMenu:(UILongPressGestureRecognizer *)recognizer{
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        [self becomeFirstResponder];
        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setTargetRect:CGRectMake([recognizer locationInView:self].x, [recognizer locationInView:self].y, 0, 0) inView:self];
        [menu setMenuVisible:YES animated:YES];
    }
}

- (void)copy:(id)sender{
    [UIPasteboard generalPasteboard].image = self.image;
}

- (void)cut:(id)sender{
    [UIPasteboard generalPasteboard].image = self.image;
    self.image = nil;
}

- (void)paste:(id)sender{
    self.image = [UIPasteboard generalPasteboard].image;
}

- (BOOL)canBecomeFirstResponder{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    if (action == @selector(copy:)) {
        return self.image;
    }else if (action == @selector(cut:)){
        return self.image;
    }else if (action == @selector(paste:)){
        return [UIPasteboard generalPasteboard].image;
    }
    return [super canPerformAction:action withSender:sender];
}

@end

演示效果如下:

表视图代理实现

UITableView提供了相应的代理方法用来方便实现cell内容的拷贝粘贴等。必须实现下面3个方法:

//长按cell时是否显示编辑菜单
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//控制编辑菜单中的按钮
- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender{
    if (action == @selector(copy:)) {
        return YES;
    }
    return NO;
}

//执行编辑菜单中点击的按钮动作
- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender{
    if (action == @selector(copy:)) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [UIPasteboard generalPasteboard].string = cell.textLabel.text;
    }
}

演示效果如下:

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS开发中上传图片可以采用以下步骤: 1.选择要上传的图片,可以使用系统提供的UIImagePickerController控制器,或者使用第三方库,例如TZImagePickerController。 2.将选中的图片转换为NSData格式。 3.使用NSURLSession或AFNetworking等网络库,将图片数据上传到服务器。 以下是一个简单的上传图片的示例代码: ``` // 选择图片 UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; imagePicker.delegate = self; [self presentViewController:imagePicker animated:YES completion:nil]; // 将选中的图片转换为NSData格式 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info { UIImage *selectedImage = info[UIImagePickerControllerOriginalImage]; NSData *imageData = UIImageJPEGRepresentation(selectedImage, 0.5); // 上传图片到服务器 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration]; NSURL *url = [NSURL URLWithString:@"http://example.com/upload.php"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // 处理服务器返回的响应 }]; [uploadTask resume]; [picker dismissViewControllerAnimated:YES completion:nil]; } ``` 其中,upload.php是服务器端接收图片的脚本文件。在服务器端,可以使用PHP等语言来处理上传的图片数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值