在iOS開(kāi)發(fā)中,我們可能有需求需要長(zhǎng)按某個(gè)控件來(lái)復(fù)制內(nèi)容。
第一種情況,直接使用tableview的方法來(lái)調(diào)用系統(tǒng)的復(fù)制剪切那個(gè)功能。
-(BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0 && indexPath.row !=0) {
return YES;
}
return NO;
}
-(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
{
if (action == @selector(copy:)) {
UsermessageCell *messageCell = (UsermessageCell *)[tableView cellForRowAtIndexPath:indexPath];
[UIPasteboard generalPasteboard].string =messageCell.messageLab.text;
}
}
第二種是自定義(這里主要是改掉系統(tǒng)拷貝的名字為復(fù)制)
//在自定義cell中的init方法加入
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressCellHandle:)];
self.longGesture = longPressGesture;
[self addGestureRecognizer:longPressGesture];
//并加上幾個(gè)方法
-(void)longPressCellHandle:(UILongPressGestureRecognizer *)gesture
{
[self becomeFirstResponder];
UIMenuController *menuController = [UIMenuController sharedMenuController];
UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"復(fù)制" action:@selector(menuCopyBtnPressed:)];
menuController.menuItems = @[copyItem];
[menuController setTargetRect:gesture.view.frame inView:gesture.view.superview];
[menuController setMenuVisible:YES animated:YES];
[UIMenuController sharedMenuController].menuItems=nil;
}
-(void)menuCopyBtnPressed:(UIMenuItem *)menuItem
{
[UIPasteboard generalPasteboard].string = self.messageLab.text;
}
-(BOOL)canBecomeFirstResponder
{
return YES;
}
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(menuCopyBtnPressed:)) {
return YES;
}
return NO;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。