通過自定義相冊來介紹photo library的使用

来源:http://www.cnblogs.com/salam/archive/2016/09/28/5914984.html
-Advertisement-
Play Games

因為我在模仿美圖秀秀的功能,在使用相冊時候,UIImagePickerController本來就是一個UINavigationController的子類,所以沒有辦法使用push,所以做了一個自定義的非UINavigationController子類的相冊。使用的api是ios8以上提供的photo ...


  因為我在模仿美圖秀秀的功能,在使用相冊時候,UIImagePickerController本來就是一個UINavigationController的子類,所以沒有辦法使用push,所以做了一個自定義的非UINavigationController子類的相冊。使用的api是ios8以上提供的photokit。

  一、獲取相冊的所有相冊集

  例如:個人收藏,最近添加,相機膠卷等。

  1.使用+ (PHFetchResult<PHAssetCollection *> *)fetchAssetCollectionsWithType:(PHAssetCollectionType)type subtype:(PHAssetCollectionSubtype)subtype options:(nullable PHFetchOptions *)options方法來獲取相冊集集合

PHFetchResult返回了結果

  2.使用+ (PHFetchResult<PHAsset *> *)fetchAssetsInAssetCollection:(PHAssetCollection *)assetCollection options:(nullable PHFetchOptions *)options方法來獲取相冊集內的所有照片資源

  

- (PHFetchResult *)fetchAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending
{
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
    PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:assetCollection options:options];
    
    return result;
}

- (NSArray <PHAsset *> *)getAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending
{
    NSMutableArray <PHAsset *> *mArr = [NSMutableArray array];
    PHFetchResult *result = [self fetchAssetsInAssetCollection:assetCollection ascending:ascending];
    [result enumerateObjectsUsingBlock:^(PHAsset *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.mediaType == PHAssetMediaTypeImage) {
            [mArr addObject:obj];
        }
    }];
    
    return mArr;
}

- (NSArray<PHAsset *> *)getAllAssetInPhotoAblumWithAscending:(BOOL)ascending
{
    NSMutableArray<PHAsset *> *assets = [NSMutableArray array];
    
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
    
    PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];
    
    [result enumerateObjectsUsingBlock:^(PHAsset *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [assets addObject:obj];
    }];
    
    return assets;
}

- (NSArray <FWPhotoAlbums *> *)getPhotoAlbums
{
    NSMutableArray<FWPhotoAlbums *> *mArr = [NSMutableArray array];
    PHFetchResult *smartAlbum = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    [smartAlbum enumerateObjectsUsingBlock:^(PHAssetCollection *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.assetCollectionSubtype != 202 && obj.assetCollectionSubtype < 212) {
            NSArray <PHAsset *> *assets = [self getAssetsInAssetCollection:obj ascending:NO];
            if ([assets count]) {
                FWPhotoAlbums *pa = [[FWPhotoAlbums alloc] init];
                pa.albumName = [self TitleOfAlbumForChinse:obj.localizedTitle];
                pa.albumImageCount = [assets count];
                pa.firstImageAsset = assets.firstObject;
                pa.assetCollection = obj;
                [mArr addObject:pa];
            }
        }
    }];
    
    PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    [userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray<PHAsset *> *assets = [self getAssetsInAssetCollection:collection ascending:YES];
        if (assets.count > 0) {
            FWPhotoAlbums *pa = [[FWPhotoAlbums alloc] init];
            pa.albumName = collection.localizedTitle;
            pa.albumImageCount = [assets count];
            pa.firstImageAsset = assets.firstObject;
            pa.assetCollection = collection;
            [mArr addObject:pa];
        }
    }];
    
    return mArr;
}

由於系統返回的相冊集名稱為英文,我們需要轉換為中文

- (NSString *)TitleOfAlbumForChinse:(NSString *)title
{
    if ([title isEqualToString:@"Slo-mo"]) {
        return @"慢動作";
    } else if ([title isEqualToString:@"Recently Added"]) {
        return @"最近添加";
    } else if ([title isEqualToString:@"Favorites"]) {
        return @"個人收藏";
    } else if ([title isEqualToString:@"Recently Deleted"]) {
        return @"最近刪除";
    } else if ([title isEqualToString:@"Videos"]) {
        return @"視頻";
    } else if ([title isEqualToString:@"All Photos"]) {
        return @"所有照片";
    } else if ([title isEqualToString:@"Selfies"]) {
        return @"自拍";
    } else if ([title isEqualToString:@"Screenshots"]) {
        return @"屏幕快照";
    } else if ([title isEqualToString:@"Camera Roll"]) {
        return @"相機膠卷";
    }
    return nil;
}

 

二、獲取照片

- (void)requestImageForAsset:(PHAsset *)asset size:(CGSize)size resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void (^)(UIImage *, NSDictionary *))completion
{
    static PHImageRequestID requestID = -1;
    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat width = MIN(WIDTH, 800);
    if (requestID >= 1 && size.width/width==scale) {
        [[PHCachingImageManager defaultManager] cancelImageRequest:requestID];
    }
    
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.resizeMode = resizeMode;
    option.networkAccessAllowed = YES;
    
    requestID = [[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage * _Nullable image, NSDictionary * _Nullable info) {
        BOOL downloadFinined = ![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey];
        if (downloadFinined && completion) {
            completion(image, info);
        }
    }];
}

 

 

 三、拍照

  [_mCamera capturePhotoAsJPEGProcessedUpToFilter:_mFilter withCompletionHandler:^(NSData *processedJPEG, NSError *error){
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:processedJPEG options:nil];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            
        }];
    }];

 

 

效果

       

 

代碼

1.模型類,存儲相冊集名稱,相片數,第一張照片以及該相冊集包含的所有照片集合

#import <Foundation/Foundation.h>
#import <photos/photos.h>

@interface FWPhotoAlbums : NSObject

@property (nonatomic, copy) NSString *albumName; //相冊名字
@property (nonatomic, assign) NSUInteger albumImageCount; //該相冊內相片數量
@property (nonatomic, strong) PHAsset *firstImageAsset; //相冊第一張圖片縮略圖
@property (nonatomic, strong) PHAssetCollection *assetCollection; //相冊集,通過該屬性獲取該相冊集下所有照片

@end
FWPhotoAlbums.h
#import "FWPhotoAlbums.h"

@implementation FWPhotoAlbums

@end
FWPhotoAlbums.m

 

2.照片管理類,負責獲取資源集合,請求照片

#import <Foundation/Foundation.h>
#import "FWPhotoAlbums.h"

@interface FWPhotoManager : NSObject

+ (instancetype)sharedManager;

- (NSArray <FWPhotoAlbums *> *)getPhotoAlbums;

- (NSArray<PHAsset *> *)getAllAssetInPhotoAblumWithAscending:(BOOL)ascending;

- (NSArray<PHAsset *> *)getAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending;

- (void)requestImageForAsset:(PHAsset *)asset size:(CGSize)size resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void (^)(UIImage *image, NSDictionary *info))completion;

- (void)requestImageForAsset:(PHAsset *)asset scale:(CGFloat)scale resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void (^)(UIImage *image))completion;

- (void)getPhotosBytesWithArray:(NSArray *)photos completion:(void (^)(NSString *photosBytes))completion;

- (BOOL)judgeAssetisInLocalAblum:(PHAsset *)asset ;
@end
FWPhotoManager.h
#import "FWPhotoManager.h"

@implementation FWPhotoManager

+ (instancetype)sharedManager
{
    static FWPhotoManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[super allocWithZone:NULL] init];
    });
    
    return manager;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [self sharedManager];
}

- (PHFetchResult *)fetchAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending
{
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
    PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:assetCollection options:options];
    
    return result;
}

- (NSArray <PHAsset *> *)getAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending
{
    NSMutableArray <PHAsset *> *mArr = [NSMutableArray array];
    PHFetchResult *result = [self fetchAssetsInAssetCollection:assetCollection ascending:ascending];
    [result enumerateObjectsUsingBlock:^(PHAsset *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.mediaType == PHAssetMediaTypeImage) {
            [mArr addObject:obj];
        }
    }];
    
    return mArr;
}

- (NSArray<PHAsset *> *)getAllAssetInPhotoAblumWithAscending:(BOOL)ascending
{
    NSMutableArray<PHAsset *> *assets = [NSMutableArray array];
    
    PHFetchOptions *option = [[PHFetchOptions alloc] init];
    
    option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
    
    PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];
    
    [result enumerateObjectsUsingBlock:^(PHAsset *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [assets addObject:obj];
    }];
    
    return assets;
}

- (NSArray <FWPhotoAlbums *> *)getPhotoAlbums
{
    NSMutableArray<FWPhotoAlbums *> *mArr = [NSMutableArray array];
    PHFetchResult *smartAlbum = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    [smartAlbum enumerateObjectsUsingBlock:^(PHAssetCollection *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.assetCollectionSubtype != 202 && obj.assetCollectionSubtype < 212) {
            NSArray <PHAsset *> *assets = [self getAssetsInAssetCollection:obj ascending:NO];
            if ([assets count]) {
                FWPhotoAlbums *pa = [[FWPhotoAlbums alloc] init];
                pa.albumName = [self TitleOfAlbumForChinse:obj.localizedTitle];
                pa.albumImageCount = [assets count];
                pa.firstImageAsset = assets.firstObject;
                pa.assetCollection = obj;
                [mArr addObject:pa];
            }
        }
    }];
    
    PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    [userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop) {
        NSArray<PHAsset *> *assets = [self getAssetsInAssetCollection:collection ascending:YES];
        if (assets.count > 0) {
            FWPhotoAlbums *pa = [[FWPhotoAlbums alloc] init];
            pa.albumName = collection.localizedTitle;
            pa.albumImageCount = [assets count];
            pa.firstImageAsset = assets.firstObject;
            pa.assetCollection = collection;
            [mArr addObject:pa];
        }
    }];
    
    return mArr;
}

- (NSString *)TitleOfAlbumForChinse:(NSString *)title
{
    if ([title isEqualToString:@"Slo-mo"]) {
        return @"慢動作";
    } else if ([title isEqualToString:@"Recently Added"]) {
        return @"最近添加";
    } else if ([title isEqualToString:@"Favorites"]) {
        return @"個人收藏";
    } else if ([title isEqualToString:@"Recently Deleted"]) {
        return @"最近刪除";
    } else if ([title isEqualToString:@"Videos"]) {
        return @"視頻";
    } else if ([title isEqualToString:@"All Photos"]) {
        return @"所有照片";
    } else if ([title isEqualToString:@"Selfies"]) {
        return @"自拍";
    } else if ([title isEqualToString:@"Screenshots"]) {
        return @"屏幕快照";
    } else if ([title isEqualToString:@"Camera Roll"]) {
        return @"相機膠卷";
    }
    return nil;
}

- (void)requestImageForAsset:(PHAsset *)asset size:(CGSize)size resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void (^)(UIImage *, NSDictionary *))completion
{
    static PHImageRequestID requestID = -1;
    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat width = MIN(WIDTH, 800);
    if (requestID >= 1 && size.width/width==scale) {
        [[PHCachingImageManager defaultManager] cancelImageRequest:requestID];
    }
    
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.resizeMode = resizeMode;
    option.networkAccessAllowed = YES;
    
    requestID = [[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage * _Nullable image, NSDictionary * _Nullable info) {
        BOOL downloadFinined = ![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey];
        if (downloadFinined && completion) {
            completion(image, info);
        }
    }];
}

- (void)requestImageForAsset:(PHAsset *)asset scale:(CGFloat)scale resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void (^)(UIImage *image))completion
{
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.resizeMode = resizeMode;//控制照片尺寸
    option.networkAccessAllowed = YES;
    
    [[PHCachingImageManager defaultManager] requestImageDataForAsset:asset options:option resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
        BOOL downloadFinined = ![[info objectForKey:PHImageCancelledKey] boolValue] && ![info objectForKey:PHImageErrorKey] && ![[info objectForKey:PHImageResultIsDegradedKey] boolValue];
        if (downloadFinined && completion) {
            CGFloat sca = imageData.length/(CGFloat)UIImageJPEGRepresentation([UIImage imageWithData:imageData], 1).length;
            NSData *data = UIImageJPEGRepresentation([UIImage imageWithData:imageData], scale==1?sca:sca/2);
            completion([UIImage imageWithData:data]);
        }
    }];
}

- (BOOL)judgeAssetisInLocalAblum:(PHAsset *)asset
{
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.networkAccessAllowed = NO;
    option.synchronous = YES;
    
    __block BOOL isInLocalAblum = YES;
    
    [[PHCachingImageManager defaultManager] requestImageDataForAsset:asset options:option resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
        isInLocalAblum = imageData ? YES : NO;
    }];
    return isInLocalAblum;
}



@end
FWPhotoManager.m

 

3.顯示相冊FWPhotoAlbumTableViewController

#import <UIKit/UIKit.h>
#import <Photos/Photos.h>

@interface FWPhotoAlbumTableViewController : UITableViewController
//最大選擇數
@property (nonatomic, assign) NSInteger maxSelectCount;
//是否選擇了原圖
@property (nonatomic, assign) BOOL isCanSelectMorePhotos;
//當前已經選擇的圖片
//@property (nonatomic, strong) NSMutableArray<ZLSelectPhotoModel *> *arraySelectPhotos;

//選則完成後回調
//@property (nonatomic, copy) void (^DoneBlock)(NSArray<ZLSelectPhotoModel *> *selPhotoModels, BOOL isSelectOriginalPhoto);
//取消選擇後回調
@property (nonatomic, copy) void (^CancelBlock)();


@end
FWPhotoAlbumTableViewController.h
#import "FWPhotoAlbumTableViewController.h"
#import "FWPhotoManager.h"
#import "UIButton+TextAndImageHorizontalDisplay.h"
#import "FWPhotoCollectionViewController.h"
#import "FWPhotosLayout.h"

@interface FWPhotoAlbumTableViewController ()
{
    NSMutableArray<FWPhotoAlbums *> *mArr;
}

@end

@implementation FWPhotoAlbumTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"相冊";
    
    mArr= [[[FWPhotoManager sharedManager] getPhotoAlbums] mutableCopy];
    
    [self initNavgationBar];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)initNavgationBar
{
    UIButton *rightBar = [UIButton buttonWithType:UIButtonTypeSystem];
    rightBar.frame = CGRectMake(0, 0, 68, 32);
    [rightBar setImage:[UIImage imageNamed:@"Camera"] withTitle:@"相機" forState:UIControlStateNormal];
    [rightBar addTarget:self action:@selector(cameraClicked) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBar];
}

- (void)cameraClicked
{
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [mArr count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    FWPhotoAlbums *album = mArr[indexPath.row];
    cell.textLabel.text =album.albumName;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%d張",album.albumImageCount];
    cell.detailTextLabel.textColor = [UIColor grayColor];
    __block UIImage *img = nil;
    [[FWPhotoManager sharedManager] requestImageForAsset:album.firstImageAsset size:CGSizeMake(60 * 3, 60 * 3) resizeMode:PHImageRequestOptionsResizeModeExact completion:^(UIImage *image, NSDictionary *info) {
        img = image;
    }];
    cell.imageView.image = img;
    cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
    cell.imageView.clipsToBounds = YES;
    return cell;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FWPhotoAlbums *model = [mArr objectAtIndex:indexPath.row];
    FWPhotosLayout *layout = [[FWPhotosLayout alloc] init];
    layout.minimumInteritemSpacing = 1.5;
    layout.minimumLineSpacing = 5.0;
    FWPhotoCollectionViewController *vc = [[FWPhotoCollectionViewController alloc] initWithCollectionViewLayout:layout model:model];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
FWPhotoAlbumTableViewController.m

 

4.顯示相冊集內所有照片FWPhotoCollectionViewController

#import <UIKit/UIKit.h>
#import <Photos/Photos.h>
#import "FWPhotoAlbums.h"

@interface FWPhotoCollectionViewController : UICollectionViewController

@property (nonatomic, strong) FWPhotoAlbums *model;

- (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)layout model:(FWPhotoAlbums *)model;

@end
FWPhotoCollectionViewController.h

 

//
//  FWPhotoCollectionViewController.m
//  FWLifeApp
//
//  Created by Forrest Woo on 16/9/23.
//  Copyright © 2016年 ForrstWoo. All rights reserved.
//

#import "FWPhotoCollectionViewController.h"
#import "FWPhotoCell.h"
#import "FWPhotoManager.h"
#import "FWPhotosLayout.h"
#import "FWDisplayBigImageViewController.h"

@interface FWPhotoCollectionViewController () <UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>
{
    NSArray<PHAsset *> *_dataSouce;
}
@property (nonatomic, strong) PHAssetCollection *assetCollection;
@end

@implementation FWPhotoCollectionViewController

static NSString * const reuseIdentifier = @"Cell";

- (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)layout model:(FWPhotoAlbums *)model
{
    if (self = [super initWithCollectionViewLayout:layout]) {
        self.model = model;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = NO;
//    self.navigationController.navigationBarHidden = YES;
    // Register cell classes
    CGRect frame = self.collectionView.frame;
    frame.origin.y+=44;
    self.collectionView.frame = frame;
    self.view.backgroundColor = [UIColor whiteColor];

    [self initSource];
}

//- (void)setModel:(FWPhotoAlbums *)model
//{
//    self.model = model;
//    
//    [self initSource];
//}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}
- (void)initSource
{
    [self.collectionView registerClass:[FWPhotoCell class] forCellWithReuseIdentifier:reuseIdentifier];
    self.title = self.model.albumName;
    self.automaticallyAdjustsScrollViewInsets = NO;
    // Do any additional setup after loading the view.
    self.assetCollection = self.model.assetCollection;
    _dataSouce = [[FWPhotoManager sharedManager] getAssetsInAssetCollection:self.assetCollection ascending:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [_dataSouce count];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FWPhotosLayout *lay = (FWPhotosLayout *)collectionViewLayout;
    return CGSizeMake([lay cellWidth],[lay cellWidth]);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FWPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    PHAsset *asset = _dataSouce[indexPath.row];
    __block UIImage *bImage = nil;
    CGSize size = cell.frame.size;
    size.width *= 3;
    size.height *= 3;
    [[FWPhotoManager sharedManager] requestImageForAsset:asset size:size resizeMode:PHImageRequestOptionsResizeModeFast completion:^(UIImage *image, NSDictionary *info) {
        bImage = image;
    }];
    
    [cell setImage:bImage];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PHAsset *asset = _dataSouce[indexPath.row];

    [[FWPhotoManager sharedManager] requestImageForAsset:asset size:PHImageManagerMaximumSize resizeMode:PHImageRequestOptionsResizeModeFast completion:^(UIImage *image, NSDictionary *info) {
        FWDisplayBigImageViewController *vc = [[FWDisplayBigImageViewController alloc] initWithImage:image];
        [self.navigationController pushViewController:vc animated:YES];
    }];
   
}
#pragma mark <UICollectionViewDelegate>

@end
FWPhotoCollectionViewController.m

 

5.佈局類

#import <UIKit/UIKit.h>

@interface FWPhotosLayout : UICollectionViewFlowLayout

@property (nonatomic, assign,readonly)CGFloat cellWidth;

@end
FWPhotosLayout.h
#import "FWPhotosLayout.h"

@interface FWPhotosLayout ()
@property NSInteger countOfRow;
@end

@implementation FWPhotosLayout

- (void)prepareLayout
{
    [super prepareLayout];
    
    self.countOfRow = ceilf([self.collectionView numberOfItemsInSection:0] / 4.0);
}

- (UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes *attris = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    NSInteger currentRow = indexPath.item / 4;
    
    CGRect frame = CGRectMake( (indexPath.item % 4) * ([self cellWidth] + 5),currentRow * ([self cellWidth] + 65), [self cellWidth], [self cellWidth]);
    attris.frame = frame;
    attris.zIndex = 1;
    
    return attris;
}

- (CGFloat)cellWidth
{
    return (WIDTH - 3 * 5) / 4;
}

- (CGSize)collectionViewContentSize
{
    return CGSizeMake(WIDTH, self.countOfRow * ([self cellWidth] + 5) + 44);
}
@end
FWPhotosLayout.m

 

 

代碼下載 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 當我們在寫應用時要複製粘貼文本框內容時,預設顯示的文字為英文字體,可按如下步驟設置,顯示中文: ...
  • 1.首先要先註冊自己的appkey在shareSDK官網裡面 2.下載shareSDK 文檔,可以根據需要下載自己需要的 如圖 3.將下載好的shareSDK 解壓後加入工程裡面 4.添加依賴庫 //必須添加的庫 必須添加的依賴庫如下(Xcode 7 下 .dylib庫尾碼名更改為 .tbd): l ...
  • 在上篇文章中實現了優酷菜單執行動畫,本文接著完善已經實現的動畫功能 本文地址:http://www.cnblogs.com/wuyudong/p/5915958.html ,轉載請註明源地址。 已經實現的菜單動畫功能存在一點BUG,那就是當快速連續點擊menu或home按鈕的時候,動畫出現進入和退出 ...
  • 前兩天上架App遇到一個比較神奇的問題,打包好的項目使用Application Loader上傳成功,但是在iTunes裡面卻找不到構建版本,App的活動頁面也沒有相應的版本。 之前瞭解IOS10對用戶的安全和隱私的增強,在申請很多私有許可權的時候都需要添加描述,但是,在使用Xcode 8對原有項目編 ...
  • 實際上都是互補的,也就是說一些原則需要利用另一些原則來實現自己。 6大原則如下: 1)單一職責原則,一個合理的類,應該僅有一個引起它變化的原因,即單一職責,就是設計的這個類功能應該只有一個; 優點:消除耦合,減小因需求變化引起代碼僵化。 2) 開-閉原則,講的是設計要對擴展有好的支持,而對修改要嚴格 ...
  • 此外不在更新 地址: ...
  • 實現類似下麵的這種佈局的方法 ...
  • 在上篇文章中實現了優酷菜單的佈局,本文接著實現動畫功能 本文地址:http://www.cnblogs.com/wuyudong/p/5914901.html,轉載請註明源地址。 新建動畫工具類AnimationUtils.java,代碼如下: 接著編寫邏輯部分代碼: 基本實現菜單的旋轉功能 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...