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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容