UIMenuController的使用

  1. 自定义一个Widget,例如XXLabel
  2. 实现 – (BOOL)canBecomeFirstResponder, 且返回YES
  3. 实现 – (BOOL)canPerformAction:withSender, 并根据需求返回YESNO(貌似可以不用实现,不显示过期文字标签)
代码如下
#import "XXLabel.h"

@implementation XXLabel

- (void)awakeFromNib
{
    [self addLongPressGesture];
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

#pragma mark - Private Method

- (void)addLongPressGesture
{
    self.userInteractionEnabled = YES;
    
    UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToCollection:)];
    [self addGestureRecognizer:longPressGR];
}

- (void)longPressToCollection:(UIGestureRecognizer *)recognizer
{
    [self becomeFirstResponder];
    
    UIMenuItem *collection = [[UIMenuItem alloc] initWithTitle:@"收藏" action:@selector(collectionAction:)];
    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setMenuItems:[NSArray arrayWithObjects:collection, nil]];
    [menu setTargetRect:self.frame inView:self.superview];
    [menu setMenuVisible:YES animated:YES];
}

- (void)collectionAction:(id)sender
{
    // 使用Block或者代理
    NSLog(@"点击了收藏");
}

@end

你可能感兴趣的:(UIMenuController的使用)