上一篇文章已经提到,在用系统的UIMenuController无法实现需求要的效果:
Paste_Image.png因此要自定义UIMenuController,具体代码如下:
- 在.h文件中
#import <UIKit/UIKit.h>
@interface XJLabel : UILabel
@end
- 在.m文件中
#import "XJLabel.h"
@implementation XJLabel
- (void)awakeFromNib {
[super awakeFromNib];
[self setup];
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self setup];
}
return self;
}
- (void)setup {
self.userInteractionEnabled = YES;
}
/**
* 让label有资格成为第一响应者
*/
- (BOOL)canBecomeFirstResponder {
return YES;
}
/**
* label能执行哪些操作(比如copy, paste等等)
* @return YES:支持这种操作
*/
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
return NO;
}
@end
- 在控制器当中
#import "ViewController.h"
#import "XJLabel.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet XJLabel *label;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick)]];
}
- (void)labelClick {
// 1.label要成为第一响应者(作用是:告诉UIMenuController支持哪些操作, 这些操作如何处理)
[self.label becomeFirstResponder];
// 2.显示MenuController
UIMenuController *menu = [UIMenuController sharedMenuController];
// 添加MenuItem
UIMenuItem *ding = [[UIMenuItem alloc] initWithTitle:@"顶" action:@selector(ding:)];
UIMenuItem *replay = [[UIMenuItem alloc] initWithTitle:@"回复" action:@selector(replay:)];
UIMenuItem *report = [[UIMenuItem alloc] initWithTitle:@"举报" action:@selector(report:)];
menu.menuItems = @[ding, replay, report];
[menu setTargetRect:self.label.bounds inView:self.label];
[menu setMenuVisible:YES animated:YES];
}
- (void)ding:(UIMenuController *)menu {
NSLog(@"%s %@", __func__ , menu);
}
- (void)replay:(UIMenuController *)menu {
NSLog(@"%s %@", __func__ , menu);
}
- (void)report:(UIMenuController *)menu {
NSLog(@"%s %@", __func__ , menu);
}
@end
通过自定义UIMenuController,运行起来,就达到了需求要的效果,如图所示
Snip20161015_6.png
网友评论