博客> 长按手势保存图片到相册
长按手势保存图片到相册
2019-11-09 03:28 评论:0 阅读:918 Sherry_ssq
ios UILongPressGestureRecognizer 长按保存图片

1、先定义一个UIImageView视图:

_QRCodeView = [[UIImageView alloc] initWithFrame:CGRectMake(100,100, 100,100]; _QRCodeView.userInteractionEnabled = YES; UILongPressGestureRecognizer*longPress=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(dealLongPress:)]; _QRCodeView.image = [UIImage imageNamed:@"服务号"]; [_QRCodeView addGestureRecognizer:longPress]; [self.view addSubview:_QRCodeView];

2、实现长按识别方法

// 长按识别二维码 -(void)dealLongPress:(UIGestureRecognizer*)gesture{

UIImageView*tempImageView=(UIImageView*)gesture.view;

//如果不加这个判断就会执行两次
if ([gesture state] == UIGestureRecognizerStateBegan) {
    NSLog(@"   %@",tempImageView.image);
    UIImageWriteToSavedPhotosAlbum(tempImageView.image, self,  @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

}

3、在回调里面做相应处理

// 指定回调方法

  • (void)image: (UIImage ) image didFinishSavingWithError: (NSError ) error contextInfo: (void ) contextInfo { NSString msg = nil; if(error != NULL){

    UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置中设置该程序允许访问相册"preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    
        if([[UIApplication sharedApplication] canOpenURL:url]) {
    
            NSURL* url =[NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url];
        }
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];

    }else{ msg = @"保存图片成功"; [XHToast showCenterWithText:msg]; } }

收藏
1
sina weixin mail 回到顶部