zoukankan      html  css  js  c++  java
  • iOS 封装一个带复制功能的UILabel

    我们发现UILabel不在为我们提供长按弹出复制等操作了, 我们来继承UILabel自己写一个带复制功能的UILabel。

    代码:

    #import "CopyLabel.h"
    
    @implementation CopyLabel
    
    - (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 = 0.25; [self addGestureRecognizer:longPress]; } // 使label能够成为响应事件 - (BOOL)canBecomeFirstResponder { return YES; } // 自定义方法时才显示对就选项菜单,即屏蔽系统选项菜单 - (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(customCopy:)){ return YES; } return NO; } - (void)customCopy:(id)sender {
    UIPasteboard
    *pasteboard = [UIPasteboard generalPasteboard]; pasteboard.string = self.text; }
    - (void)longPressAction:(UIGestureRecognizer *)recognizer {
    if (recognizer.state == UIGestureRecognizerStateBegan) { [self becomeFirstResponder]; UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"拷贝" action:@selector(customCopy:)]; UIMenuController *menuController = [UIMenuController sharedMenuController]; menuController.menuItems = [NSArray arrayWithObjects:copyItem, nil]; [menuController setTargetRect:self.frame inView:self.superview]; [menuController setMenuVisible:YES animated:YES]; } } @end

    使用:

    - (void)viewDidLoad {
       [super viewDidLoad];
    CopyLabel
    *copy = [[CopyLabel alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width,50)]; copy.text = @"一个带复制功能的Label"; copy.textAlignment = NSTextAlignmentCenter; copy.backgroundColor = [UIColor yellowColor]; copy.textColor = [UIColor redColor]; copy.font = [UIFont boldSystemFontOfSize:16]; [self.view addSubview:copy]; }
  • 相关阅读:
    C#开源框架
    8 种 NoSQL 数据库系统对比
    安装补丁“此更新不适用于你的计算机”解决办法
    .net开源资料
    winform程序退出
    jquery.chained与jquery.chained.remote使用以及区别
    存储过程使用回滚
    C# Panel中绘图如何出现滚动条
    C#结构体的特点浅析
    如何用堆栈和循环结构代替递归调用--递归转换为非递归的10条军规
  • 原文地址:https://www.cnblogs.com/xuzb/p/9541872.html
Copyright © 2011-2022 走看看