首页 > 代码库 > UILabel 支持copy功能
UILabel 支持copy功能
给UILabel扩充Copy功能
实现的原理:注册通知 添加手势识别 调用粘贴板
具体实现 创建UICopyLabel类 继承UILabel
代码
UICopyLabel.h文件
#import <UIKit/UIKit.h>@interface UICopyLabel : UILabel@end
UICopyLabel.m文件
#import "UICopyLabel.h"@implementation UICopyLabel- (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc];}- (id)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { [self attachTapHandlerAndAddObserver]; } return self;}-(id)initWithCoder:(NSCoder *)aDecoder{ self = [super initWithCoder:aDecoder]; if (self) { [self attachTapHandlerAndAddObserver]; } return self;}-(void)attachTapHandlerAndAddObserver{ self.userInteractionEnabled = YES; //用户交互的总开关 UILongPressGestureRecognizer *touch = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; [self addGestureRecognizer:touch]; self.exclusiveTouch = YES; [touch release]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelLabelBackgroundColor) name:UIMenuControllerDidHideMenuNotification object:nil];}-(BOOL)canBecomeFirstResponder{ return YES;}//还需要针对复制的操作覆盖两个方法:// 可以响应的方法-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{ self.backgroundColor = [UIColor clearColor]; return (action == @selector(copy:));}//针对于响应方法的实现-(void)copy:(id)sender{ UIPasteboard *pboard = [UIPasteboard generalPasteboard]; pboard.string = self.text;}-(void)handleTap:(UIGestureRecognizer*) recognizer{ [self becomeFirstResponder]; UIMenuItem *copyLink = [[[UIMenuItem alloc] initWithTitle:@"复制全部内容" action:@selector(copy:)]autorelease]; [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObjects:copyLink, nil]]; [[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview]; [[UIMenuController sharedMenuController] setMenuVisible:YES animated: YES]; self.backgroundColor = [UIColor lightGrayColor];}-(void)cancelLabelBackgroundColor{ self.backgroundColor = [UIColor clearColor];}@end
使用:把你需要支持copy的UILabel换成UICopyLabel 就OK了
UILabel 支持copy功能
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。