一.使用 UIPickerViewController 自定义相机和相册功能
备用:
1. 在info.plist里面添加Localized resources can be mixed设置为YES(表示是否允许应用程序获取框架库内语言)
2.提示框
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - 秀贝] 打开访问开关" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//确定按钮点击事件处理
}]];
[self presentViewController:alert animated:YES completion:nil];
** 第一.调用相机方法 (系统版)**
- (void)takePhoto{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.allowsEditing = YES;/** 设置拍照后的图片可被编辑 */
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//录制视频时长,默认10s
picker.videoMaximumDuration = 15;
//相机类型(拍照、录像...)字符串需要做相应的类型转换
picker.mediaTypes = @[(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage];
picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
//设置摄像头模式(拍照,录制视频)为录像模式
picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
[self presentViewController:picker animated:YES completion:^{
[UIApplication sharedApplication].statusBarHidden = YES;;
}];
}else{
NSLog(@"模拟机无法打开照相机,请在真机使用");
}
}
** 第二.调用相机方法 (自定义版)如图 **
55D48AA898FC2FB26F99D0E9DBFF1055.jpg 1.属性相关
@property (nonatomic , copy) NSString *openCamera;
@property (nonatomic , strong) MSUPickerControlView *controlView;//自定义的类文件实现自定义视图
2.自定义类文件,继承于UIView
1) MSUPickerControlView.h 中的代码
#import <UIKit/UIKit.h>
@interface MSUPickerControlView : UIView
@property (nonatomic , strong) UIButton *closeBtn;
@property (nonatomic , strong) UIButton *pickBtn;
@property (nonatomic , copy) void(^pickBtnTouchDownBlock)(UIButton *btn);
@property (nonatomic , copy) void(^pickBtnClickBlock)(UIButton *btn);
@property (nonatomic , strong) UIProgressView *processView;
@property (nonatomic , strong) UIButton *flashBtn;
@property (nonatomic , copy) void(^flashBtnClickBlock)(UIButton *btn);
@property (nonatomic , strong) UIButton *positionBtn;
@property (nonatomic , copy) void(^positionBtnClickBlock)(UIButton *btn);
@end
2) MSUPickerControlView.m 中的代码
#import "MSUPickerControlView.h"
#import "MSUPathTools.h"
#define HEXCOLOR(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
//masonry
#define MAS_SHORTHAND
#define MAS_SHORTHAND_GLOBALS
#import "Masonry.h"
#define SelfWidth [UIScreen mainScreen].bounds.size.width
#define SelfHeight [UIScreen mainScreen].bounds.size.height
@implementation MSUPickerControlView
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
[self createView];
}
return self;
}
- (void)createView{
self.closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_closeBtn.adjustsImageWhenHighlighted = NO;
_closeBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
[_closeBtn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-close"] forState:UIControlStateNormal];
_closeBtn.layer.cornerRadius = 10;
_closeBtn.layer.shouldRasterize = YES;
_closeBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;
[self addSubview:_closeBtn];
[_closeBtn makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.top).offset(24);
make.left.equalTo(self.left).offset(14);
make.width.equalTo(20);
make.height.equalTo(20);
}];
UIView *bgView = [[UIView alloc] init];
bgView.backgroundColor = HEXCOLOR(0xffffff);
[self addSubview:bgView];
[bgView makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(self.bottom).offset(0);
make.left.equalTo(self.left).offset(0);
make.width.equalTo(SelfWidth);
make.height.equalTo(150);
}];
self.pickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_pickBtn.adjustsImageWhenHighlighted = NO;
_pickBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
// [_pickBtn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-close"] forState:UIControlStateNormal];
_pickBtn.backgroundColor = HEXCOLOR(0xf7d721);
[_pickBtn setTitle:@"按住拍" forState:UIControlStateNormal];
[_pickBtn setTitleColor:HEXCOLOR(0xffffff) forState:UIControlStateNormal];
_pickBtn.titleLabel.font = [UIFont systemFontOfSize:14];
_pickBtn.layer.shadowColor = HEXCOLOR(0xf7d721).CGColor;
_pickBtn.layer.shadowOpacity = 0.6;
_pickBtn.layer.shadowOffset = CGSizeZero;
_pickBtn.layer.shadowRadius = 5;
_pickBtn.layer.cornerRadius = 39;
_pickBtn.layer.shouldRasterize = YES;
_pickBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;
[self addSubview:_pickBtn];
[_pickBtn makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(bgView.top).offset(36);
make.left.equalTo(self.left).offset(SelfWidth*0.5-49);
make.width.equalTo(78);
make.height.equalTo(78);
}];
[_pickBtn addTarget:self action:@selector(pickBtnClick:) forControlEvents:UIControlEventTouchDown];
[_pickBtn addTarget:self action:@selector(pickBtnCancelClick:) forControlEvents:UIControlEventTouchUpInside];
self.processView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
[self addSubview:_processView];
[_processView makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(bgView.top).offset(-5);
make.left.equalTo(bgView.left).offset(0);
make.width.equalTo(SelfWidth);
make.height.equalTo(5);
}];
_processView.trackTintColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];
_processView.progressTintColor = HEXCOLOR(0xf7d721);
//设置进度
// _processView.progress = 0.2;
self.positionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_positionBtn.adjustsImageWhenHighlighted = NO;
_positionBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
[_positionBtn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-camera-exchange"] forState:UIControlStateNormal];
[self addSubview:_positionBtn];
[_positionBtn makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(_processView.top).offset(-23);
make.right.equalTo(self.right).offset(-39);
make.width.equalTo(30);
make.height.equalTo(23);
}];
[_positionBtn addTarget:self action:@selector(positionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
self.flashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_flashBtn.adjustsImageWhenHighlighted = NO;
_flashBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
[_flashBtn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-light-auto"] forState:UIControlStateNormal];
[self addSubview:_flashBtn];
[_flashBtn makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(_processView.top).offset(-23);
make.right.equalTo(_positionBtn.left).offset(-35);
make.width.equalTo(21.5);
make.height.equalTo(24.5);
}];
[_flashBtn addTarget:self action:@selector(flashBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark - 点击事件
- (void)positionBtnClick:(UIButton *)sender{
if (self.positionBtnClickBlock) {
self.positionBtnClickBlock(sender);
}
}
- (void)flashBtnClick:(UIButton *)sender{
if (self.flashBtnClickBlock) {
self.flashBtnClickBlock(sender);
}
}
- (void)pickBtnClick:(UIButton *)sender{
if (self.pickBtnTouchDownBlock) {
self.pickBtnTouchDownBlock(sender);
}
}
- (void)pickBtnCancelClick:(UIButton *)sender{
if (self.pickBtnClickBlock) {
self.pickBtnClickBlock(sender);
}
}
3. /* 拍照和录视频 */
- (void)takePictureAndCamera{
// MSUPermissionTool是封装相关权限的类,可根据自己情况写自己的
[MSUPermissionTool getCamerasPermission:^(NSInteger authStatus) {
if (authStatus == 1) {
self.openCamera = @"开启";
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *picker = [[UIImagePickerController alloc]init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.delegate = self;
// picker.allowsEditing = YES;/** 设置拍照后的图片可被编辑 */
//录制视频时长,默认10s
picker.videoMaximumDuration = 10;
//相机类型(拍照、录像...)字符串需要做相应的类型转换
// picker.mediaTypes = @[(NSString *)kUTTypeImage,(NSString *)kUTTypeMovie];
picker.mediaTypes = @[(NSString *)kUTTypeMovie];
picker.videoQuality = UIImagePickerControllerQualityTypeIFrame960x540;
//设置摄像头模式(拍照,录制视频)为录像模式
picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
CGSize screenBounds = [UIScreen mainScreen].bounds.size;
CGFloat cameraAspectRatio = 4.0f/3.0f;
CGFloat camViewHeight = screenBounds.width * cameraAspectRatio;
CGFloat scale = screenBounds.height / camViewHeight;
picker.cameraViewTransform = CGAffineTransformMakeTranslation(0, (screenBounds.height - camViewHeight) / 2.0);
picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, scale, scale);
// CGAffineTransform transform = CGAffineTransformMakeTranslation(0.0f, -200.0f);
// transform = CGAffineTransformScale(transform, 1.0f, 0.5f);
// picker.cameraViewTransform = transform;
// 自定义录像视频页面
picker.showsCameraControls = NO;
self.controlView = [[MSUPickerControlView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
_controlView.backgroundColor = [UIColor clearColor];
picker.cameraOverlayView = _controlView; // 自定义控件view
// 关闭按钮
[_controlView.closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
// 前后摄像头
_controlView.positionBtnClickBlock = ^(UIButton *btn) {
btn.selected = !btn.selected;
picker.cameraDevice = btn.selected?UIImagePickerControllerCameraDeviceFront:UIImagePickerControllerCameraDeviceRear;
};
// 闪光灯状态
static NSInteger x;
_controlView.flashBtnClickBlock = ^(UIButton *btn) {
x += 1;
if (x == 3) {
x = 0;
}
switch (x) {
case 0:
{
[btn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-light-auto"] forState:UIControlStateNormal];
picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
}
break;
case 1:
{
[btn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-light-on"] forState:UIControlStateNormal];
picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOn;
}
break;
case 2:
{
[btn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-light-close"] forState:UIControlStateNormal];
picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOff;
}
break;
default:
break;
}
};
// 拍摄按钮
__weak typeof(self) weakSelf = self;
_controlView.pickBtnTouchDownBlock = ^(UIButton *btn) {
// 判断与设备方向
weakSelf.motionManager = [[CMMotionManager alloc] init];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
if (weakSelf.motionManager.accelerometerAvailable) {
weakSelf.motionManager.accelerometerUpdateInterval = 1;
[weakSelf.motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
if (error) {
[weakSelf.motionManager stopAccelerometerUpdates];
NSLog(@"error");
} else {
// NSLog(@"x 加速度--> %f\n y 加速度--> %f\n z 加速度--> %f\n", accelerometerData.acceleration.x, accelerometerData.acceleration.y, accelerometerData.acceleration.z);
// 根据 accelerometerData.acceleration.x/y/z来区分手机横竖屏状态。
if (accelerometerData.acceleration.x > accelerometerData.acceleration.y && accelerometerData.acceleration.y < 0) {
NSLog(@"竖屏");
weakSelf.statusStr = @"竖屏";
} else if (accelerometerData.acceleration.x < 0 && accelerometerData.acceleration.y > 0){
NSLog(@"横屏");
weakSelf.statusStr = @"横屏";
} else if (accelerometerData.acceleration.x > 0 && accelerometerData.acceleration.y > 0){
NSLog(@"横屏");
weakSelf.statusStr = @"横屏";
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[weakSelf.motionManager stopDeviceMotionUpdates];
[weakSelf.motionManager stopAccelerometerUpdates];
});
}
}];
} else {
NSLog(@"This device has no accelerometer");
}
// 开始录像
[picker startVideoCapture];
weakSelf.time = 0;
weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timeChange:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop]addTimer:weakSelf.timer forMode:NSRunLoopCommonModes];
};
_controlView.pickBtnClickBlock = ^(UIButton *btn) {
if (weakSelf.timer) {
[MSUHUD showStatusWithString:@"正在处理"];
[picker stopVideoCapture];
[weakSelf.timer invalidate];
weakSelf.timer = nil;
[UIView animateWithDuration:1 animations:^{
weakSelf.controlView.processView.progress = 0;
}];
} else{
}
};
[self.navigationController presentViewController:picker animated:YES completion:^{
[UIApplication sharedApplication].statusBarHidden = YES;;
}];
}else{
NSLog(@"模拟机无法打开照相机,请在真机使用");
}
}else{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - 秀贝] 打开访问开关" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//确定按钮点击事件处理
}]];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
- (void)timeChange:(NSTimer *)timer{
_time++;
CGFloat value = _time;
// NSLog(@"-----%f,%ld",value/10,_time);
[UIView animateWithDuration:1 animations:^{
_controlView.processView.progress = value/10;
}];
if (value >= 10) {
[self.timer invalidate];
self.timer = nil;
}
}
第三.选择照片功能
-(void)LocalPhoto
{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.delegate = self;
//设置选择后的图片可被编辑
picker.allowsEditing = YES;
[self presentViewController:picker animated:YES completion:nil];
}
第四.选择视频功能
- (void)pickedMedia{
// 1、 获取摄像设备
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (device) {
[MSUPermissionTool getPhotosPermission:^(NSInteger authStatus) {
if (authStatus == 1) {
dispatch_async(dispatch_get_main_queue(), ^{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
// 选择视频方式
imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
imagePicker.delegate = self;
// imagePicker.allowsEditing = YES;
[self presentViewController:imagePicker animated:YES completion:^{
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}];
});
}else{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 照片 - 秀贝] 打开访问开关" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//确定按钮点击事件处理
}]];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
}
** 第四、代理方法**
#pragma mark UIImagePickerControllerDelegate
//适用获取所有媒体资源,只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
NSLog(@"===========%@",info);
//判断资源类型
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
//如果是图片
UIImage *pickedImage = nil;
if ([picker allowsEditing]) {
pickedImage = info[UIImagePickerControllerEditedImage];
}else{
pickedImage = info[UIImagePickerControllerOriginalImage];
}
NSLog(@"图片是%@",pickedImage);
// self.imageView.image = info[UIImagePickerControllerEditedImage];
// //压缩图片
// NSData *fileData = UIImageJPEGRepresentation(self.imageView.image, 1.0);
// //保存图片至相册
UIImageWriteToSavedPhotosAlbum(pickedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
// //上传图片
// [self uploadImageWithData:fileData];
}else{
[MSUHUD dismiss];
//如果是视频
NSURL *url = info[UIImagePickerControllerMediaURL];
CGSize videoSize = [MSUCameraPhotoVc getVideoSizeWithURL:url];
NSLog(@"视频链接是%@",url);
NSLog(@"宽 :%f , 高 : %f",videoSize.width,videoSize.height);
CGFloat videoLenth = [MSUCameraPhotoVc getVideoDuration:url];
NSLog(@"视频时长 %f",videoLenth);
UISaveVideoAtPathToSavedPhotosAlbum([url path], self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
// self.hidesBottomBarWhenPushed = YES;
// self.selectedViewController = [self.viewControllers objectAtIndex:2];
if (videoLenth < 3) {
[MSUHUD showFileWithString:@"最短拍摄时间不能低于三秒,请重新拍摄"];
} else{
MSUFilterController *filter = [[MSUFilterController alloc] init];
filter.videoUrl = url;
filter.statusStr = self.statusStr;
[picker pushViewController:filter animated:YES];
self.hidesBottomBarWhenPushed = NO;
}
// //播放视频
// _moviePlayer.contentURL = url;
// [_moviePlayer play];
// //保存视频至相册(异步线程)
// NSString *urlStr = [url path];
//
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
//
// UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
// }
// });
// NSData *videoData = [NSData dataWithContentsOfURL:url];
// //视频上传
// [self uploadVideoWithData:videoData];
}
// [self dismissViewControllerAnimated:YES completion:nil];
}
/** 取消按钮回调 */
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[self dismissViewControllerAnimated:YES completion:nil];
}
/* 图片保存完毕的回调 */
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
if (error) {
NSLog(@"保存照片过程中发生错误,错误信息:%@",error.localizedDescription);
}else{
NSLog(@"照片保存成功.");
}
}
/* 视频保存完毕的回调 */
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
if (error) {
NSLog(@"保存视频过程中发生错误,错误信息:%@",error.localizedDescription);
}else{
NSLog(@"视频保存成功.");
}
}
第五、下挂商品图标,预览、删除等
1. 导入第三方 MSImagePickerController,导入相关属性
/// 添加图片
@property (nonatomic , strong) UIButton *addBtn;
@property (nonatomic , strong) UIImage *pickIma;
@property (retain, nonatomic) NSMutableArray* array;
@property (nonatomic , strong) UIView *picView;
2.点击按钮,打开照片
- (void)addBtnClick:(UIButton *)sender{
MSImagePickerController* picker = [[MSImagePickerController alloc] init];
picker.msDelegate = self;
picker.maxImageCount = 4;
picker.doneButtonTitle = @"确定";
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:true completion:^{
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}];
}
3.实现代理方法 MSImagePickerController Delegate
#pragma mark - MSImagePickerController Delegate method
- (void)imagePickerControllerDidCancel:(MSImagePickerController *)picker; {
[picker dismissViewControllerAnimated:true completion:^{
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}];
NSLog(@"do cancel");
}
- (void)imagePickerControllerDidFinish:(MSImagePickerController *)picker {
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
self.array = [picker.images mutableCopy];
self.addBtn.hidden = YES;
self.picView = [[UIView alloc] init];
// 图片放置位置 frame自设
_picView.frame = CGRectMake(0,270+60 , WIDTH, 80);
_picView.backgroundColor = HEXCOLOR(0xffffff);
[self.view addSubview:_picView];
for (UIImage* img in self.array) {
NSData* data = [MSUStringTools compressOriginalImage:img withScale:1];
if (data != nil) {
for (NSInteger i = 0; i < self.array.count; i++) {
UIButton *privateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
// 根据pickView 自设frame
privateBtn.frame = CGRectMake(14 + 90*i, 0, 80, 80);
[privateBtn setImage:self.array[i] forState:UIControlStateNormal];
privateBtn.adjustsImageWhenHighlighted = NO;
privateBtn.tag = 1650+i;
[_picView addSubview:privateBtn];
[privateBtn addTarget:self action:@selector(privateBtnTouchInClick:) forControlEvents:UIControlEventTouchDown];
UILongPressGestureRecognizer *tap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressClick:)];
tap.delegate = self;
tap.minimumPressDuration = 1.0;
tap.numberOfTouchesRequired = 1;
[privateBtn addGestureRecognizer:tap];
}
}
}
[picker dismissViewControllerAnimated:true completion:^{
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
// QLPreviewController* ql = [[QLPreviewController alloc] init];
// ql.dataSource = self;
// [self presentViewController:ql
// animated:true
// completion:nil];
}];
}
- (void)imagePickerControllerOverMaxCount:(MSImagePickerController *)picker; // 选择的图片超过上限的时候调用
{
NSString* message = [NSString stringWithFormat:@"你最多只能选择%ld张图片。", picker.maxImageCount];
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
message:message
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil];
[alert show];
}
4.实现预览功能
#pragma mark - QLPreviewController Delegate method
/*!
* @abstract Returns the number of items that the preview controller should preview.
* @param controller The Preview Controller.
* @result The number of items.
*/
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller; {
return self.array.count;
}
/*!
* @abstract Returns the item that the preview controller should preview.
* @param index The index of the item to preview.
* @result An item conforming to the QLPreviewItem protocol.
*/
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index; {
NSString* path = [NSString stringWithFormat:@"%@/%ld.png", [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject], (long)index];
NSURL* url = [[NSURL alloc] initFileURLWithPath:path];
return (id <QLPreviewItem>)url;
}
5.实现长按删除,再添加等
/* 删除图片按钮事件 */
- (void)chachaBtnClick:(UIButton *)sender{
NSInteger a = sender.tag-1633;
[self.array removeObjectAtIndex:a];
// UIButton *btn = [self.picView viewWithTag:a+1650];
// [sender removeFromSuperview];
// [btn removeFromSuperview];
// [self.picView layoutIfNeeded];
[self.picView removeFromSuperview];
self.picView = [[UIView alloc] init];
_picView.frame = CGRectMake(0,270+60 , WIDTH, 80);
_picView.backgroundColor = HEXCOLOR(0xffffff);
[self.view addSubview:_picView];
for (NSInteger i = 0; i < self.array.count; i++) {
UIButton *privateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
privateBtn.frame = CGRectMake(14 + 90*i, 0, 80, 80);
[privateBtn setImage:self.array[i] forState:UIControlStateNormal];
privateBtn.adjustsImageWhenHighlighted = NO;
[_picView addSubview:privateBtn];
[privateBtn addTarget:self action:@selector(privateBtnTouchInClick:) forControlEvents:UIControlEventTouchDown];
UILongPressGestureRecognizer *tap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressClick:)];
tap.delegate = self;
tap.minimumPressDuration = 1.0;
tap.numberOfTouchesRequired = 1;
[privateBtn addGestureRecognizer:tap];
}
if (self.array.count == 0) {
[self.picView removeFromSuperview];
self.addBtn.hidden = NO;
}
}
- (void)longPressClick:(UILongPressGestureRecognizer *)sender{
if(sender.state == UIGestureRecognizerStateBegan)
{
for (NSInteger i = 0; i < self.array.count; i++) {
UIButton *privateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
privateBtn.frame = CGRectMake(14 + 60 + 90*i, 0, 20, 20);
privateBtn.layer.cornerRadius = 10;
privateBtn.clipsToBounds = YES;
privateBtn.layer.shouldRasterize = YES;
privateBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;
privateBtn.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
[privateBtn setImage:[MSUPathTools showImageWithContentOfFileByName:@"WechatIMG448"] forState:UIControlStateNormal];
privateBtn.adjustsImageWhenHighlighted = NO;
privateBtn.tag = 1633+i;
[self.picView addSubview:privateBtn];
[privateBtn addTarget:self action:@selector(chachaBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}
}
}
网友评论