陈斌彬的技术博客

Stay foolish,stay hungry

在UITableView上实用剪贴板的两种方法

一:在自定义cell里面使用

其实,在cell的使用跟在label里面的用法基本一样

方法:

- (BOOL)canBecomeFirstResponder{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    if (action == @selector(cut:)){
        return NO;
    }
   else if(action == @selector(copy:)){
        return YES;
    }
    else if(action == @selector(paste:)){
        return NO;
    }
    else if(action == @selector(select:)){
        return NO;
    }
    else if(action == @selector(selectAll:)){
        return NO;
    }
    else{
        return [super canPerformAction:action withSender:sender];
    }
}

然后呢,当然就是实现copy方法拉。。

- (void)copy:(id)sender {
    NSLog(@"copy");
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
   [pasteboard setString:[[self textLabel]text]];
  }

不过还有最重要的一步,上此方法,它的意思是用来激发copy菜单哦。

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    [[self delegate] performSelector:@selector(showMenu:)
      withObject:self afterDelay:0.9f];
[super setHighlighted:highlighted animated:animated];
 }

至于生成菜单,大家应该已经经过上一篇的阅读,已经很熟悉了,看代码:

//显示菜单
- (void)showMenu:(id)cell {
    if ([cell isHighlighted]) {
         [cell becomeFirstResponder];
        UIMenuController * menu = [UIMenuController sharedMenuController];
        [menu setTargetRect: [cell frame] inView: [self view]];
        [menu setMenuVisible: YES animated: YES];
    }
}

OK,剩下的至于如何实用自定义的cell,大家应该已经很熟练了吧,我就不在一一介绍了,自此,第一种使用剪贴板的方法介绍完

二:第二种就更简单了,因为__MAC_NA,__IPHONE_5_)以后已经放出了3个方法,非常好用,我直接就上方法拉

- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {      

    return YES; 
}       

- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {     

     if (action == @selector(copy:)) {     

        return YES;    

        }              

        return NO;  
}       

- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {            
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];        

    if (action == @selector(copy:)) {          

        [UIPasteboard generalPasteboard].string = cell.textLabel.text;     

    }           

}

Resource Reference