本文主要是介绍[iOS]UIMenuController简单使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
简单使用UIMenuController给UILabel添加复制、粘贴、分享功能。
Demo:https://download.csdn.net/download/u012881779/10628704
#import "GACopyLabel.h"@implementation GACopyLabel- (void)awakeFromNib {[super awakeFromNib];
}- (instancetype)initWithFrame:(CGRect)frame {if (self = [super initWithFrame:frame]) {self.userInteractionEnabled = YES;UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];[self addGestureRecognizer:longPress];}return self;
}/*** 成为第一响应者*/
- (BOOL)canBecomeFirstResponder {return YES;
}/*** 这个方法决定了MenuController的菜单项内容* 返回YES,就代表MenuController会有action菜单项* action == @selector(cut:) || action == @selector(copy:) || action == @selector(paste:) || action == @selector(select:) || action == @selector(selectAll:) || action == @selector(delete:)*/
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {if (action == @selector(copy:) || action == @selector(cut:) || action == @selector(paste:) || action == @selector(delete:) || action == @selector(custom:) || action == @selector(share:)) {// 需要展示的系统菜单,改变系统菜单文本语言 PROJECT-Locallzations-添加Chinese(Simplified)return YES;}return NO;/*// 禁用所有长按文本框操作if ([UIMenuController sharedMenuController]) {[UIMenuController sharedMenuController].menuVisible = NO;}return NO;*/
}#pragma mark - 长按手势事件- (void)longPress:(UILongPressGestureRecognizer *)longPress {// 让该控件成为第一响应者, 还需要实现方法canBecomeFirstResponder[self becomeFirstResponder];if (longPress.state == UIGestureRecognizerStateBegan) {UIMenuController *popMenu = [UIMenuController sharedMenuController];UIMenuItem *shareItem = [[UIMenuItem alloc] initWithTitle:@"分享" action:@selector(share:)];[popMenu setMenuItems:[NSArray arrayWithObjects:shareItem, nil]];UIMenuItem *customItem = [[UIMenuItem alloc] initWithTitle:@"自定义" action:@selector(custom:)];[popMenu setMenuItems:[NSArray arrayWithObjects:shareItem,customItem, nil]];// 方向[popMenu setArrowDirection:UIMenuControllerArrowDown];// 部分选取[popMenu setTargetRect:self.frame inView:self.superview];// 设置菜单中可见[popMenu setMenuVisible:YES animated:YES];NSLog(@"ddd");}
}#pragma mark - 复制- (void)copy:(nullable id)sender {if (self.text.length > 0 && self.text != nil) {// 剪切板[UIPasteboard generalPasteboard].string = self.text;}
}#pragma mark - 剪切- (void)cut:(nullable id)sender {if (self.text.length > 0 && self.text != nil) {[UIPasteboard generalPasteboard].string = self.text;}self.text = nil;
}#pragma mark - 粘贴- (void)paste:(nullable id)sender {NSString *pasteboard = [UIPasteboard generalPasteboard].string;if (pasteboard.length > 0 && pasteboard) {self.text = [self.text stringByAppendingString:pasteboard];}
}#pragma mark - 删除- (void)delete:(nullable id)sender {self.text = @"";
}#pragma mark - 分享- (void)share:(nullable id)sender {}#pragma mark - 自定义- (void)custom:(nullable id)sender {self.text = @"custom: 执行自定义操作";
}@end
示意图:
这篇关于[iOS]UIMenuController简单使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!