上一篇文章已經(jīng)提到,在用系統(tǒng)的UIMenuController無(wú)法實(shí)現(xiàn)需求要的效果:
因此要自定義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有資格成為第一響應(yīng)者
*/
- (BOOL)canBecomeFirstResponder {
return YES;
}
/**
* label能執(zhí)行哪些操作(比如copy, paste等等)
* @return YES:支持這種操作
*/
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
return NO;
}
@end
- 在控制器當(dāng)中
#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要成為第一響應(yīng)者(作用是:告訴UIMenuController支持哪些操作, 這些操作如何處理)
[self.label becomeFirstResponder];
// 2.顯示MenuController
UIMenuController *menu = [UIMenuController sharedMenuController];
// 添加MenuItem
UIMenuItem *ding = [[UIMenuItem alloc] initWithTitle:@"頂" action:@selector(ding:)];
UIMenuItem *replay = [[UIMenuItem alloc] initWithTitle:@"回復(fù)" action:@selector(replay:)];
UIMenuItem *report = [[UIMenuItem alloc] initWithTitle:@"舉報(bào)" 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
通過(guò)自定義UIMenuController,運(yùn)行起來(lái),就達(dá)到了需求要的效果,如圖所示