问题描述
- iOS lable怎么实现复制粘贴选择全选
-
开发中遇到 要求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
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
[self attachTapHandler];
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
//为了能接收到事件(能成为第一响应者),我们需要覆盖一个方法:
-(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
解决方案二:
那就用 TextView 啊,设置成不可编辑就相当于 label 使用了