創(chuàng)作靈感:
工作中經(jīng)常會用到一些需要和朋友分享的內(nèi)容,如邀請碼了。雖然功能很簡單,但是這些東西不需要和數(shù)據(jù)進(jìn)行交互,可以直接將其封裝成一個控件,有需要的時候可以直接調(diào)用豈不痛快。提高代碼的可重復(fù)性。
我所封裝的這個控件的思路主要是繼承UIlabel,通過長按或者雙擊的手勢,來達(dá)到觸發(fā)的效果,然后通過富文本,給文字加一個底色,這樣就可以知道自己已經(jīng)選中了文字,以此達(dá)到目的,廢話不多說,直接上代碼。
#import <UIKit/UIKit.h>
@interface CSRCopyLabel : UILabel
@end
以下是.m文件
#import "CSRCopyLabel.h"
@implementation CSRCopyLabel
-(BOOL)canBecomeFirstResponder
{
return YES;
}
// 可以響應(yīng)的方法
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
return (action == @selector(copy:));
}
//UILabel默認(rèn)是不接收事件的,我們需要自己添加touch事件
-(void)attachTapHandler
{
self.userInteractionEnabled = YES; //用戶交互的總開關(guān)
//雙擊
UITapGestureRecognizer *touch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
touch.numberOfTapsRequired = 2;
[self addGestureRecognizer:touch];
//長按手勢
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self addGestureRecognizer:longPressGesture];
}
//綁定事件
- (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:@"復(fù)制" action:@selector(copy:)];
[[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObjects:copyLink, nil]];
[[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
[[UIMenuController sharedMenuController] setMenuVisible:YES animated: YES];
//加個背景色
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:self.text];
NSDictionary *dic = @{NSBackgroundColorAttributeName:GreyTwoLevel, };
[str addAttributes:dic range:NSMakeRange(0, self.text.length)];
self.attributedText = str;
}
//針對于響應(yīng)方法的實現(xiàn)
-(void)copy:(id)sender
{
UIPasteboard *pboard = [UIPasteboard generalPasteboard];
pboard.string = self.text;
//取消背景顏色
[self cancleLabelBackColor];
}
//取消label文字的背景顏色
- (void)cancleLabelBackColor
{
NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:self.text];
NSDictionary *dic = @{NSBackgroundColorAttributeName:[UIColor whiteColor], };
[str addAttributes:dic range:NSMakeRange(0, self.text.length)];
self.attributedText = str;
}
+ (void)cancleLabelBackColor
{
[[self alloc] cancleLabelBackColor];
}
@end
具體的用法也很簡單,直接導(dǎo)入頭文件,就像使用UILabel一樣就可以使用,長按復(fù)制功能是默認(rèn)開啟的,但有時候可能不需要這個功能,直接將其userInteractionEnabled設(shè)置為NO即可。