可以长按复制的label, 带有高亮显示
先看效果
思路
新建NYLCopyLabel
继承自UILabel
, 然后添加长按手势, 把text赋值给粘贴板, 当长按的label时候, label的背景显示高亮状态, 当复制按钮消失, 高亮取消. (利用UIMenuControllerWillHideMenuNotification
的通知监听复制按钮消失)
使用方法
NYLCopyLabel * label = [ NYLCopyLabel new ] ;
[ self . view addSubview: label] ;
封装的NYLCopyLabel类
NYLCopyLabel.m
#import "NYLCopyLabel.h"
@interface NYLCopyLabel ( )
@property ( nonatomic, strong) UIPasteboard * pasteboard;
@end
@implementation NYLCopyLabel
- ( instancetype) initWithFrame: ( CGRect ) frame {
if ( self = [ super initWithFrame: frame] ) {
self . pasteboard = [ UIPasteboard generalPasteboard] ;
[ self addLongPressGes] ;
[ [ NSNotificationCenter defaultCenter] addObserver: self selector: @selector ( menuHideMenuNotification) name: UIMenuControllerWillHideMenuNotification object: nil ] ;
}
return self ;
}
- ( void) addLongPressGes {
self . userInteractionEnabled = YES ;
UILongPressGestureRecognizer * longPress = [ [ UILongPressGestureRecognizer alloc] initWithTarget: self action: @selector ( actionLongPregressGes: ) ] ;
[ self addGestureRecognizer: longPress] ;
}
- ( void) actionLongPregressGes: ( UILongPressGestureRecognizer * ) ges {
if ( ges. state == UIGestureRecognizerStateBegan ) {
[ self becomeFirstResponder] ;
UIMenuController * menuCtrl = [ UIMenuController sharedMenuController] ;
[ menuCtrl setTargetRect: self . frame inView: self . superview] ;
[ menuCtrl setMenuVisible: YES animated: YES ] ;
self . backgroundColor = [ UIColor blueColor] ;
}
}
- ( BOOL ) canBecomeFirstResponder {
return YES ;
}
- ( BOOL ) canPerformAction: ( SEL ) action withSender: ( id) sender {
if ( action == @selector ( copy: ) ) {
return YES ;
}
return NO ;
}
- ( void) copy: ( id) sender {
self . pasteboard. string = self . text;
}
- ( void) menuHideMenuNotification {
self . backgroundColor = nil ;
}
- ( void) dealloc {
[ [ NSNotificationCenter defaultCenter] removeObserver: self name: UIMenuControllerWillHideMenuNotification object: nil ] ;
}
@end
NYLCopyLabel.h
#import < UIKit / UIKit . h>
NS_ASSUME_NONNULL_BEGIN
@interface NYLCopyLabel : UILabel
@end
NS_ASSUME_NONNULL_END