当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS长按UIlabel实现可复制功能

iOS长按UIlabel实现可复制功能

2019年07月24日  | 移动技术网IT编程  | 我要评论

数学分析习题集,300521,美腿图

前言

相信大家都知道在ios中有三个控件自身是支持拷贝,粘贴的,如:uitextfield,uitextview,uiwebview。但是,有时候我们会遇到需要长按uilabel,弹出“复制”item,来实现可复制。那该怎么办呢?下面就来一起看看吧。

首先uikit中提供给我们几个类

在开始之前,我们需要自定义一个wincopylabel继承uilable

- (instancetype)initwithframe:(cgrect)frame {
 if (self = [super initwithframe:frame]) {
  [self pressaction];
 }
 return self;
}
// 初始化设置
- (void)pressaction {
 self.userinteractionenabled = yes;
 uilongpressgesturerecognizer *longpress = [[uilongpressgesturerecognizer alloc] initwithtarget:self action:@selector(longpressaction:)];
 longpress.minimumpressduration = 1;
 [self addgesturerecognizer:longpress];
}

1、uiresponder:通过这个类实现uilabel可以响应事件(我们知道uilabel是不能成为响应者的,所以这里需要重写),控制需要响应的事件

 // 使label能够成为响应事件
 - (bool)canbecomefirstresponder {
  return yes;
 }
 // 控制响应的方法
 - (bool)canperformaction:(sel)action withsender:(id)sender {
  return action == @selector(customcopy:);
 }

2、uipasteboard:该类支持写入和读取数据,类似剪贴板

 - (void)customcopy:(id)sender {
 uipasteboard *pasteboard = [uipasteboard generalpasteboard];
 pasteboard.string = self.text;
 }

3、uimenucontroller:可以通过这个类实现在点击内容,或者长按内容时展示出复制、剪贴、粘贴等选择的项,每个选项都是一个uimenuitem对象

- (void)longpressaction:(uigesturerecognizer *)recognizer {
 [self becomefirstresponder];
 uimenuitem *copyitem = [[uimenuitem alloc] initwithtitle:@"拷贝" action:@selector(customcopy:)];
 [[uimenucontroller sharedmenucontroller] setmenuitems:[nsarray arraywithobjects:copyitem, nil]];
 [[uimenucontroller sharedmenucontroller] settargetrect:self.frame inview:self.superview];
 [[uimenucontroller sharedmenucontroller] setmenuvisible:yes animated:yes];
}

补充:

一、uiresponderstandardeditactions:这是苹果给nsobject写的一个分类,其中包含了我们常用的复制,粘贴,全选等方法

 - (void)cut:(nullable id)sender  ns_available_ios(3_0);
 - (void)copy:(nullable id)sender  ns_available_ios(3_0);
 - (void)paste:(nullable id)sender  ns_available_ios(3_0);
 - (void)select:(nullable id)sender  ns_available_ios(3_0);
 - (void)selectall:(nullable id)sender  ns_available_ios(3_0);
 - (void)delete:(nullable id)sender   ns_available_ios(3_2);

当我们,选中弹出的item时,系统会调用上面对应的方法

二、.以下是剪贴板中可以放置的内容(除了字符串,也可以拷贝图片,url等)

      1.uipasteboardtypeliststring 字符串数组, 包含kuttypeutf8plaintext

      2.uipasteboardtypelisturl url数组,包含kuttypeurl

      3.uipasteboardtypelistimage 图形数组, 包含kuttypepng 和kuttypejpeg

      4.uipasteboardtypelistcolor 颜色数组

总结

以上就是这篇文章的全部内容了,希望能对各位ios开发者们有所帮助,如果有疑问大家可以留言交流。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网