使用方法:
使用方法相當簡單,和系統(tǒng)的UIlabel使用方法一樣烈拒,只需要設置相應位置即可滓侍。
.m中具體代碼:
#import "CopyLabel.h"
@implementation CopyLabel
-(BOOL)canBecomeFirstResponder {
return YES;
}
// 可以響應的方法
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
return (action == @selector(copy:));
}
//針對于響應方法的實現
-(void)copy:(id)sender {
UIPasteboard *pboard = [UIPasteboard generalPasteboard];
pboard.string = self.text;
}
//UILabel默認是不接收事件的绍傲,我們需要自己添加touch事件
-(void)attachTapHandler {
self.userInteractionEnabled = YES;
UILongPressGestureRecognizer *touch = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self addGestureRecognizer:touch];
}
//綁定事件
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self attachTapHandler];
}
return self;
}
-(void)awakeFromNib {
[super awakeFromNib];
[self attachTapHandler];
}
-(void)handleTap:(UIGestureRecognizer*) recognizer {
[self becomeFirstResponder];
UIMenuItem *copyLink = [[UIMenuItem alloc] initWithTitle:@"復制"action:@selector(copy:)];
[[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObjects:copyLink, nil]];
[[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
[[UIMenuController sharedMenuController] setMenuVisible:YES animated: YES];
}
@end