本人在網(wǎng)上看到的大部分關(guān)于自定義剪貼板的文章,按照文章上的方法操作,點(diǎn)擊復(fù)制時(shí),鍵盤(pán)總會(huì)退出,對(duì)此經(jīng)歷了百般折磨.終于在stackoverflow上找到了解決辦法.
一般場(chǎng)景就像聊天界面一樣,必然后一個(gè)輸入框,和一個(gè)需要剪切板的文本,就像上圖一樣的聊天界面.
處理方法,自定義輸入框的類如:MATextView
MATextView.h
@interface MATextView : UITextView
@property (nonatomic, weak) UIResponder *inputNextResponder;
@end
MATextView.m
@implementation MATextView
- (UIResponder *)nextResponder {
if (_inputNextResponder != nil)
return _inputNextResponder;
else
return [super nextResponder];
}
@end
在需要剪貼板的地方的長(zhǎng)按方法如下編寫(xiě)
- (void)chatMessageBtnLongTap:(UILongPressGestureRecognizer *)longTap
{
// 菜單已經(jīng)打開(kāi)不需重復(fù)操作
UIMenuController *menu=[UIMenuController sharedMenuController];
if (menu.isMenuVisible)return;
if ([_textView isFirstResponder]) {
_textView.inputNextResponder = self;//關(guān)鍵代碼
}else{
[self becomeFirstResponder];
}
UIMenuItem *copy = [[UIMenuItem alloc] initWithTitle:@"復(fù)制"action:@selector(copyItem:)];
[menu setMenuItems:@[copy]];
[menu setTargetRect:self.chatMessageBackgroundView.frame inView:self.contentView];
[menu setMenuVisible:YES animated:YES];
self.chatMessageBackgroundView.highlighted = YES;
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(copyBtnWillHidden) name:UIMenuControllerWillHideMenuNotification object:nil];
}
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
if(action ==@selector(copyItem:)){
return YES;
}
return [super canPerformAction:action withSender:sender];
}
- (BOOL)canBecomeFirstResponder{
return YES;
}
-(void)copyItem:(id)sender{
[[UIPasteboard generalPasteboard]setString:_chatMessage.content];
}
- (void)copyBtnWillHidden{
UIView *superView = self.superview.superview.superview;
KFChatToolView *toolView = [superView viewWithTag:kKF5ChatToolViewTag];
if ([toolView isKindOfClass:[KFChatToolView class]]) {
toolView.textView.inputNextResponder = nil;
}
self.chatMessageBackgroundView.highlighted = NO;
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
注意: 需要在UITableView的代理中添加scrollViewWillBeginDragging:手指滾動(dòng)時(shí),隱藏菜單
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
// 隱藏菜單
UIMenuController *menu=[UIMenuController sharedMenuController];
[menu setMenuVisible:NO];
// 隱藏鍵盤(pán)
[self.textView resignFirstResponder];
}