長(zhǎng)按實(shí)現(xiàn)復(fù)制或者轉(zhuǎn)發(fā)功能

在項(xiàng)目中想要添加一個(gè)長(zhǎng)按Cell彈出UIMenuController的功能,當(dāng)我在

tableview中添加時(shí)是可以彈出來的,然而當(dāng)在自定義cell.m文件中添加UILongPressGestureRecognizer時(shí),可以觸發(fā)事件,但是MenuController死活不出來,搗鼓了半天無果,只好google搜索,最后發(fā)現(xiàn)忘記實(shí)現(xiàn)下面的第三個(gè)方法。下面把解決方案記錄一下。

要實(shí)現(xiàn)長(zhǎng)按彈出菜單欄需要做到以下三點(diǎn):

1.在view(cell)或者viewController中調(diào)用-becomeFirstResponder方法;

2.你的view或者viewcontroller需要實(shí)現(xiàn) -canBecomeFirstResponder 方法,返回YES;

3.你的view或者viewcontroller需要實(shí)現(xiàn)-canPerformAction:action withSender:sender 方法來隱藏或者現(xiàn)實(shí)響應(yīng)的item;

cell中關(guān)鍵代碼展示:

1.添加longpress事件

-(instancetype)initWithStyle:(UITableViewCellStyle)style

reuseIdentifier:(NSString*)reuseIdentifier{

if(self=[super?initWithStyle:style?reuseIdentifier:reuseIdentifier])

{

[self ?addGestureRecognizer:

[[UILongPressGestureRecognizer?alloc]initWithTarget:selfaction:@selector(longTap:)]];

}

return self;

}

2.處理長(zhǎng)按事件

-(void)longTap:(UILongPressGestureRecognizer*)longRecognizer

{

if(longRecognizer.state==UIGestureRecognizerStateBegan)

{

[self becomeFirstResponder];

UIMenuController*menu=[UIMenuController?sharedMenuController];

UIMenuItem*copyItem = [[UIMenuItem?alloc]?initWithTitle:@"復(fù)制"action:@selector(copyItemClicked:)];

UIMenuItem*resendItem = [[UIMenuItem?alloc]?initWithTitle:@"轉(zhuǎn)發(fā)"action:@selector(resendItemClicked:)];

[menu ?setMenuItems:[NSArray?arrayWithObjects:copyItem,resendItem,nil]];

[menu ?setTargetRect:self.bounds?inView:self];

[menu ?setMenuVisible:YES?animated:YES];

}

}

3.實(shí)現(xiàn)默認(rèn)方法

#pragma mark處理action事件

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{

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

returnYES;

}else if?(action==@selector(resendItemClicked:)){

returnYES;

}

return[super?canPerformAction:action?withSender:sender];

}

#pragma mark實(shí)現(xiàn)成為第一響應(yīng)者方法

-(BOOL)canBecomeFirstResponder{

returnYES;

}

4.處理item點(diǎn)擊事件

#pragma mark method

-(void)resendItemClicked:(id)sender{

NSLog(@"轉(zhuǎn)發(fā)");

//通知代理

}


//復(fù)制到系統(tǒng)粘貼板

-(void)copyItemClicked:(id)sender{

NSLog(@"復(fù)制");

UIPasteboard*pasteBoard = [UIPasteboard generalPasteboard];

NSArray* array = [self.text componentsSeparatedByString:@":"];

pasteBoard.string= [array ?lastObject];

}

最后編輯于
?著作權(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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容