iOS 长按复制文本

来源:互联网 发布:iphone8必备软件推荐 编辑:程序博客网 时间:2024/06/05 03:28

- (void)viewDidLoad {

    [superviewDidLoad];

    self.view.backgroundColor=[UIColorwhiteColor];

    self.title=@"地址";

    

    _label=[[UILabelalloc]init];

    _label.text=[NSStringstringWithFormat:@"%@%@%@%@",self.sheng,self.shi,self.qu,self.xiangxi];

    _label.textColor=[UIColorredColor];

    _label.userInteractionEnabled=YES;

    _label.frame=CGRectMake(20,80,300, 30);

    

    NSLog(@"==%@==%@ ==%@还有==%@",self.sheng,self.shi,self.qu,self.xiangxi);

    

    [self.viewaddSubview:_label];

    

    [selfcreateGesture];

    

}


-(void)createGesture{

    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizeralloc] initWithTarget:selfaction:@selector(longPressCellHandle:)];

    

    longPressGesture.minimumPressDuration =2;

    [self.labeladdGestureRecognizer:longPressGesture];


}

-(void)longPressCellHandle:(UILongPressGestureRecognizer *)gesture

    {

        

//        [self becomeFirstResponder];

        

        if (gesture.state==UIGestureRecognizerStateEnded) {

            

            UIMenuController *menuController = [UIMenuControllersharedMenuController];

            

            UIMenuItem *copyItem = [[UIMenuItemalloc] initWithTitle:@"复制"action:@selector(menuCopyBtnPressed:)];

            

            menuController.menuItems =@[copyItem];

            

            [menuController setTargetRect:gesture.view.frameinView:gesture.view.superview];

            

            [menuController setMenuVisible:YESanimated:YES];

            

            [UIMenuControllersharedMenuController].menuItems=nil;

        }

       

        

    }

    

-(void)menuCopyBtnPressed:(UIMenuItem *)menuItem

    

    {

        

        [UIPasteboardgeneralPasteboard].string =self.label.text;

        

    }

-(BOOL)canBecomeFirstResponder

    

    {

        

        returnYES;

        

    }

    

    -(BOOL)canPerformAction:(SEL)action withSender:(id)sender

    

    {

        

        if (action ==@selector(menuCopyBtnPressed:)) {

            

            returnYES;

            

        }

        

        returnNO;

        

    }