为UILabel添加手势事件,实现复制操作

2016-03-25  本文已影响244人  maniacRadish
 #import "ViewController.h"
//引入第三方框架
 #import "MBProgressHUD+ZJ.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *fuzhi;
@property (nonatomic,strong) UIPasteboard *pasteboard;
@end
@implementation ViewController
//懒加载粘贴对象
- (UIPasteboard *)pasteboard{
     if (_pasteboard != nil)   return _pasteboard;
          _pasteboard = [UIPasteboard generalPasteboard];    
          NSLog(@"%@",_pasteboard); 
         return _pasteboard;
    }

- (void)viewDidLoad  {
       [super viewDidLoad];
      //打开交互界面
       self.fuzhi.userInteractionEnabled = YES;
      //创建长按手势对象
       UILongPressGestureRecognizer  *tapGesture =[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onClickUILable:)];
      //为label添加手势对象
       [self.fuzhi addGestureRecognizer:tapGesture];
    }
//长按label调用的方法
-(void)onClickUILable(UILongPressGestureRecognizer *)sender{
     //判断手势的状态
      if (sender.state == UIGestureRecognizerStateBegan) {
           //长按手势开始
           self.pasteboard.string =self.fuzhi.text;
      }else if (sender.state == UIGestureRecognizerStateEnded){
           //长按手势结束
           if (self.pasteboard == nil) {
            [MBProgressHUD showError:@"复制失败"];           
           } else {
            [MBProgressHUD showSuccess:@"已复制"];
        }
     }
 }
上一篇下一篇

猜你喜欢

热点阅读