//
//  UILabel+CopyExtern.m
//  CopyLabel
//
//  Created by XingBo on 14-4-1.
//  Copyright (c) 2014年 XingBo. All rights reserved.
//

#import "UILabel+CopyExtern.h"

@implementation UILabel (CopyExtern)


-(BOOL)canBecomeFirstResponder
{
    return YES;
}

// 可以响应的方法
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    return (action == @selector(copyText:));
}

//针对于响应方法的实现
-(void)copyText:(id)sender
{
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    /**
     fix帖子详情页 楼主发帖复制崩溃bug
     因为某些富文本label只设置了attributedText，导致self.text为nil崩溃
     */
    if (self.text) {
        pboard.string = self.text;
    }else{
        pboard.string = self.attributedText.string;
    }
    
}

//UILabel默认是不接收事件的，我们需要自己添加touch事件
-(void)attachTapHandler{
    
    self.userInteractionEnabled = YES;  //用户交互的总开关
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [self addGestureRecognizer:longPress];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerWillShowMenuNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerWillHideMenuNotification object:nil];

}

#pragma mark - notifation methods

- (void)menuShow:(NSNotification *)sender
{
    if (self.isFirstResponder) {
        self.backgroundColor = [UIColor grayColor];
    }
    
}

- (void)menuHide:(NSNotification *)sender
{
    self.backgroundColor = [UIColor clearColor];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


-(void)handleTap:(UIGestureRecognizer*) recognizer
{
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        
        [self becomeFirstResponder];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuShow:) name:UIMenuControllerWillShowMenuNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuHide:) name:UIMenuControllerWillHideMenuNotification object:nil];
        
        [[UIMenuController sharedMenuController] setMenuItems:nil];
        UIMenuItem *copyLink = [[UIMenuItem alloc] initWithTitle:@"复制"
                                                          action:@selector(copyText:)];
        [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObjects:copyLink, nil]];
        [[UIMenuController sharedMenuController] setTargetRect:self.frame inView:self.superview];
        [[UIMenuController sharedMenuController] setMenuVisible:YES animated: YES];
        // label复制选中时的背景颜色
        self.backgroundColor = [UIColor clearColor];
    }
    
}





@end
