UILabelCopy.m 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. //
  2. // UILabelCopy.m
  3. // smartRhino
  4. //
  5. // Created by niuzhen on 2020/2/7.
  6. // Copyright © 2020 tederen. All rights reserved.
  7. //
  8. #import "UILabelCopy.h"
  9. @interface UILabelCopy()
  10. @property (nonatomic, strong) UIPasteboard *pasteboard;
  11. @end
  12. @implementation UILabelCopy
  13. - (void)awakeFromNib
  14. {
  15. [super awakeFromNib];
  16. self.numberOfLines = 0;
  17. self.pasteboard = [UIPasteboard generalPasteboard];
  18. [self attachLongTapHandle];
  19. }
  20. - (instancetype)init {
  21. if (self = [super init]) {
  22. self.numberOfLines = 0;
  23. self.pasteboard = [UIPasteboard generalPasteboard];
  24. [self attachLongTapHandle];
  25. }
  26. return self;
  27. }
  28. - (void)attachLongTapHandle {
  29. self.userInteractionEnabled = YES;
  30. UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] initWithActionBlock:^(id _Nonnull sender) {
  31. UILongPressGestureRecognizer *press = (UILongPressGestureRecognizer *)sender;
  32. if (press.state == UIGestureRecognizerStateBegan) {
  33. // UILabel成为第一响应者
  34. [self becomeFirstResponder];
  35. UIMenuItem *copyMenuItem = [[UIMenuItem alloc]initWithTitle:@"复制" action:@selector(copyAction:)];
  36. UIMenuItem *pasteMenueItem = [[UIMenuItem alloc]initWithTitle:@"全选" action:@selector(selectAll:)];
  37. UIMenuItem *cutMenuItem = [[UIMenuItem alloc]initWithTitle:@"摘录" action:@selector(returnAction:)];
  38. UIMenuController *menuVC = [UIMenuController sharedMenuController];
  39. [menuVC setMenuItems:[NSArray arrayWithObjects:copyMenuItem, pasteMenueItem,cutMenuItem, nil]];
  40. [menuVC setTargetRect:self.frame inView:self.superview];
  41. [menuVC setMenuVisible:YES animated:YES];
  42. }
  43. }];
  44. [self addGestureRecognizer:longPress];
  45. }
  46. - (BOOL)canBecomeFirstResponder {
  47. return YES;
  48. }
  49. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
  50. if (action == @selector(copyAction:)) {
  51. return YES;
  52. }
  53. if (action == @selector(selectAll:)) {
  54. return YES;
  55. }
  56. if (action == @selector(returnAction:)) {
  57. return YES;
  58. }
  59. return NO;
  60. }
  61. - (void)copyAction:(id)sender {
  62. NSLog(@"copy");
  63. self.pasteboard.string = self.text;
  64. }
  65. - (void)selectAll:(id)sender {
  66. NSLog(@"selectAll");
  67. }
  68. - (void)returnAction:(id)sender {
  69. NSLog(@"cut");
  70. }
  71. @end