陈斌彬的技术博客

Stay foolish,stay hungry

iOS—UIPasteboard/UIMenuController

剪贴板的使用以及自定义剪贴板。

系统剪贴板的直接调用

其实整个过程非常的简单,我就用我写的一个自定义UILable来说明调用系统剪贴板。

首先,因为苹果只放出来了 UITextView,UITextField,webView三个控件的剪贴板,所以一般控件的剪贴板都被禁用了,因此,我们首先要做的就是把这属性放出来,其实就是实现三个简单的方法,方法如下:

响应方法

- (BOOL)canBecomeFirstResponder{
    returnYES;
}

//"反馈"关心的功能,即放出你需要的功能,比如你要放出copy,你就返回YES,否则返回NO;
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    if (action ==@selector(copy:)){
        returnYES;
    }
    else if (action ==@selector(paste:)){
        return YES;
    }
    else if (action ==@selector(cut:)){
        returnNO;
    }
    else if(action ==@selector(select:)){
        returnNO;
    }
    else if (action ==@selector(delete:)){
        returnNO;
    }
   return NO;
}

OK,开放控件的剪贴板功能已经放出,剩下的就是实现了

//UILabel默认是不接收事件的,我们需要自己添加touch事件
-(void)attachTapHandler{
    self.userInteractionEnabled =YES;  //用户交互的总开关
    UITapGestureRecognizer *touch = [[UITapGestureRecognizeralloc] initWithTarget:selfaction:@selector(handleTap:)];
    touch.numberOfTapsRequired =1;
    [selfaddGestureRecognizer:touch];
    [touch release];
}
响应点击事件
-(void)handleTap:(UIGestureRecognizer*) recognizer{
     [selfbecomeFirstResponder];
    UIMenuController *menu = [UIMenuControllersharedMenuController];
    [menu setTargetRect:self.frameinView:self.superview];
    [menu setMenuVisible:YESanimated:YES];
}

OK,此处已经可以点击出COPY菜单了,下面就是对你copy和paste的实现了

//针对于copy的实现
-(void)copy:(id)sender{

    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = self.text;
}

- (void)paste:(id)sender{

    self.textAlignment =UITextAlignmentRight;
    UIPasteboard *pboard = [UIPasteboardgeneralPasteboard];
    self.text = [NSStringstringWithFormat:@"粘贴内容:%@",pboard.string];
    NSLog(@"pboard.string : %@",pboard.string);
}

Resource Reference