天天省钱快报

CCCopyLabel.m 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // CCCopyLabel.m
  3. // YouHuiProject
  4. //
  5. // Created by 小花 on 2018/7/11.
  6. // Copyright © 2018年 kuxuan. All rights reserved.
  7. //
  8. #import "CCCopyLabel.h"
  9. @implementation CCCopyLabel
  10. -(BOOL)canBecomeFirstResponder {
  11. return YES;
  12. }
  13. // 可以响应的方法
  14. -(BOOL)canPerformAction:(SEL)action withSender:(id)sender {
  15. if (action == @selector(newFunc)) {
  16. return YES;
  17. }
  18. return NO;
  19. }
  20. //针对于响应方法的实现
  21. -(void)copy:(id)sender {
  22. UIPasteboard *pboard = [UIPasteboard generalPasteboard];
  23. if (self.textStr.length > 0) {
  24. pboard.string = self.textStr;
  25. }else {
  26. pboard.string = self.text;
  27. }
  28. }
  29. //UILabel默认是不接收事件的,我们需要自己添加touch事件
  30. -(void)attachTapHandler {
  31. self.userInteractionEnabled = YES;
  32. UILongPressGestureRecognizer *touch = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
  33. [self addGestureRecognizer:touch];
  34. }
  35. //绑定事件
  36. - (id)initWithFrame:(CGRect)frame {
  37. self = [super initWithFrame:frame];
  38. if (self) {
  39. [self attachTapHandler];
  40. [[NSNotificationCenter defaultCenter] addObserverForName:UIMenuControllerWillHideMenuNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
  41. self.backgroundColor = [UIColor whiteColor];
  42. }];
  43. }
  44. return self;
  45. }
  46. -(void)awakeFromNib {
  47. [super awakeFromNib];
  48. [self attachTapHandler];
  49. }
  50. -(void)handleTap:(UIGestureRecognizer*) recognizer {
  51. if (recognizer.state == UIGestureRecognizerStateEnded) {
  52. return;
  53. }else if (recognizer.state == UIGestureRecognizerStateBegan){
  54. [self becomeFirstResponder];
  55. // self.backgroundColor = UIColorRGB(236, 236, 236, 1.0);
  56. self.backgroundColor = [UIColor colorWithRed:236/255.f green:236/255. blue:236/255. alpha:1.f];
  57. UIMenuItem * item = [[UIMenuItem alloc]initWithTitle:@"复制" action:@selector(newFunc)];
  58. [[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
  59. [UIMenuController sharedMenuController].menuItems = @[item];
  60. [UIMenuController sharedMenuController].menuVisible = YES;
  61. }
  62. }
  63. -(void)newFunc{
  64. UIPasteboard *pboard = [UIPasteboard generalPasteboard];
  65. if (self.textStr.length > 0) {
  66. pboard.string = self.textStr;
  67. }else {
  68. pboard.string = self.text;
  69. }
  70. }
  71. @end