iOS開發 圖片多選功能

今天加班 閑來無事 解一些小白之憂,iOS開發 圖片添加 多選與單選這個功能貌似太常見,目前還沒精力自己去完整的功能.廢話不說了上代碼.先看一下效果圖:

addImage.gif

此功能我用了兩個第三方庫:

https://github.com/iphone5solo/PYPhotoBrowser
https://github.com/banchichen/TZImagePickerController

PYPhotoBrowser使用Cocoapods安裝的方式:pod "PYPhotoBrowser" 然后導入主頭文件#import <PYPhotoBrowser.h>
TZImagePickerController使用Cocoapods安裝的方式:pod 'TZImagePickerController' 然后導入主頭文件#import "TZImagePickerController.h

如果不懂這兩個第三方 分別的作用可以打開git地址 看看文檔
接受的代理為TZImagePickerControllerDelegate,PYPhotosViewDelegate
定義一個@property (nonatomic, weak) PYPhotosView *publishPhotosView;屬性 保存選擇的圖片
點擊選擇添加圖片按鈕調用方法:

-(void)ininPhotoView{
    // 1. 常見一個發布圖片時的photosView
    PYPhotosView *publishPhotosView = [PYPhotosView photosView];
    publishPhotosView.py_x = 5;
    publishPhotosView.py_y = 10;
    // 2.1 設置本地圖片
    publishPhotosView.images = nil;
    // 3. 設置代理
    publishPhotosView.delegate = self;
    publishPhotosView.photosMaxCol = 4;//每行顯示最大圖片個數
    publishPhotosView.imagesMaxCountWhenWillCompose = 3;//最多選擇圖片的個數
    // 4. 添加photosView
    [self.view addSubview:publishPhotosView];
    self.publishPhotosView = publishPhotosView;
}

需要完成的代理方法

#pragma mark - PYPhotosViewDelegate
- (void)photosView:(PYPhotosView *)photosView didAddImageClickedWithImages:(NSMutableArray *)images{
    // 在這里做當點擊添加圖片按鈕時,你想做的事。
    [self getPhotos];
}

// 進入預覽圖片時調用, 可以在此獲得預覽控制器,實現對導航欄的自定義

- (void)photosView:(PYPhotosView *)photosView didPreviewImagesWithPreviewControlelr:(PYPhotosPreviewController *)previewControlelr{
    NSLog(@"進入預覽圖片");
}

進入相冊的方法:

-(void)getPhotos{
    CCDefineWeakSelf;
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3-weakSelf.photos.count delegate:weakSelf];
    // 你可以通過block或者代理,來得到用戶選擇的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets,BOOL isSelectOriginalPhoto){
        NSLog(@"photos===%@",photos);
        for (UIImage *image in photos) {
            [weakSelf requestData:image];//requestData:圖片上傳方法 在這里就不貼出來了
        }
        [weakSelf.photos addObjectsFromArray:photos];
    [self.publishPhotosView reloadDataWithImages:weakSelf.photos];
    }];
    [weakSelf presentViewController:imagePickerVc animated:YES completion:nil];
}

大功告成,驚不驚喜?意不意外? 代碼這么少 這就是我不喜歡造輪子的原因之一,當然也是我工資低的原因之一.....

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容