zoukankan      html  css  js  c++  java
  • UI基础--UILabel

    苹果在iOS8之后,UILabel这个控件不在给我们提供好长按进行复制的操作,接下来我们自己写一个关于复制Lable上面的文字;

    创建一个label继承UILabel;

    代码如下:

    -(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;
    }
    
    //UILabel默认是不接收事件的,我们需要自己添加touch事件
    -(void)attachTapHandler {
        
        self.userInteractionEnabled = YES;
        UILongPressGestureRecognizer *touch = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        [self addGestureRecognizer:touch];
    }
    
    //绑定事件
    - (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:@"复制"
                                                          action:@selector(copy:)];
        [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObjects:copyLink, nil]];
        [[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
        [[UIMenuController sharedMenuController] setMenuVisible:YES animated: YES];
    }

    这样就可以实现了.

    下面这段代码是改变Label上面的文字颜色

     NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:@"我:是"];
        NSRange redRange = NSMakeRange(0, [[noteStr string] rangeOfString:@":"].location);
        [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange];
        [label setAttributedText:noteStr] ;
  • 相关阅读:
    java-泛型及上界下界详解
    【CSDN】Spring+Spring MVC+Mybatis实战项目之云笔记项目
    mybatis
    spring笔记-spring mvc表单
    spring笔记-第一个spring mvc 项目
    巡风源码阅读与分析---AddPlugin()方法
    巡风源码阅读与分析---view.py
    BUGKUctf-web-writeup
    陕西省网络空间安全技术大赛部分题目writeup
    “百度杯”CTF比赛(二月场)-web-writeup
  • 原文地址:https://www.cnblogs.com/LzwBlog/p/5707324.html
Copyright © 2011-2022 走看看