開發中遇到 要求lable 要求可以選擇全選 也就是select方法的實現 各位大牛 求解答
代碼直接發你,將就著看下 ,自定義一個 uilabel就行
//
// Cuslabel.m
// test
//
// Created by mac on 15-3-21.
// Copyright (c) 2015年 mac. All rights reserved.
//
#import "Cuslabel.h"
@implementation Cuslabel
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
//為了能接收到事件(能成為第一響應者),我們需要覆蓋一個方法:
-(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;
}
//有了以上三個方法,我們就能處理copy了,當然,在能接收到事件的情況下:
//UILabel默認是不接收事件的,我們需要自己添加touch事件
-(void)attachTapHandler
{
self.userInteractionEnabled = YES; //用戶交互的總開關
// UITapGestureRecognizer *touch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
// touch.numberOfTapsRequired = 2;
UILongPressGestureRecognizer *jk=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
[self addGestureRecognizer:jk];
// [UIResponder ]
}
//綁定事件
-(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];
}
//同上
-(void)awakeFromNib
{
[super awakeFromNib];
[self attachTapHandler];
}
@end