本人在网上看到的大部分关于自定义剪贴板的文章,按照文章上的方法操作,点击复制时,键盘总会退出,对此经历了百般折磨.终于在stackoverflow上找到了解决办法.
一般场景就像聊天界面一样,必然后一个输入框,和一个需要剪切板的文本,就像上图一样的聊天界面.
处理方法,自定义输入框的类如: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
在需要剪贴板的地方的长按方法如下编写
- (void)chatMessageBtnLongTap:(UILongPressGestureRecognizer *)longTap
{
// 菜单已经打开不需重复操作
UIMenuController *menu=[UIMenuController sharedMenuController];
if (menu.isMenuVisible)return;
if ([_textView isFirstResponder]) {
_textView.inputNextResponder = self;//关键代码
}else{
[self becomeFirstResponder];
}
UIMenuItem *copy = [[UIMenuItem alloc] initWithTitle:@"复制"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:手指滚动时,隐藏菜单
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
// 隐藏菜单
UIMenuController *menu=[UIMenuController sharedMenuController];
[menu setMenuVisible:NO];
// 隐藏键盘
[self.textView resignFirstResponder];
}
网友评论
http://www.cnblogs.com/silence-cnblogs/p/6824426.html
GitHub:
https://github.com/Silence-GitHub/MenuControllerDemo
https://github.com/Silence-GitHub/SWMenuController