說明:這是一個(gè)帶長按復(fù)制功能的Label擴(kuò)展
前按:實(shí)現(xiàn)該功能需要用到的類有,UIMenuItem鼻听、UIMenuController柒室、UIPasteboard。
代碼:
// ?.h文件
#import@interface UILabel (CopyLabel)
- (void)copyLabelText;
@end
- (void)copyLabelText{
? ? [self setUp];
}
- (void)setUp{
? ? self.userInteractionEnabled = YES;
[self addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self ? ? action:@selector(longPressAction:)]];
}
- (void)longPressAction:(UILongPressGestureRecognizer *)press{
//設(shè)置為第一響應(yīng)仙辟,通過第一響應(yīng)者UIMenuController可以獲得支持那些操作信息
? ? [self becomeFirstResponder];
? ? UIMenuController *menu = [UIMenuController sharedMenuController];
? ? UIMenuItem *copyMenu = [[UIMenuItem alloc] initWithTitle:@"復(fù)制" action:@selector(copyMenuAction)];
? ? menu.menuItems = @[copyMenu];
? ? [menu setTargetRect:self.bounds inView:self];
? ? ?[menu setMenuVisible:YES animated:YES];
}
- (void)copyMenuAction{
? ? ?if (!self.text) return;
? ? ?UIPasteboard *paste = [UIPasteboard generalPasteboard];
? ? ?paste.string = self.text;
}
// 用于UIMenuController顯示,缺一不可
-(BOOL)canBecomeFirstResponder{
? ? ?return YES;
}
// 用于UIMenuController顯示鳄梅,缺一不可
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
? ? ?if (action == @selector(copyMenuAction)){
? ? ? ? ? ? ? return YES;
? ? ?}
? ? ?return NO;//隱藏系統(tǒng)默認(rèn)的菜單項(xiàng)
}