UITableView 相册-判断多选相册的位置

相册页面实现如下多选功能

我实现的时候使用了 UITableView

@interface PTASysAlbumVC : BaseViewController<UITableViewDelegate,UITableViewDataSource,PTSysAssetPickerControllerDelegate,PhotoAlbumClickedDelegate>{
    ..........
    UITableView   *_cvPhotoList;
    .......
}
//
//  PTASysAlbumVC.m
//  PTAlbum
//
//  Created by LiLiLiu on 15/4/24.
//  Copyright (c) 2015年 putao.Inc. All rights reserved.
//

#import "PTASysAlbumVC.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import "PTASysAssetGroupVC.h"
#import "AssetHelper.h"
#import "Util.h"
#import "NDDateTools.h"
#import "UIColor+Help.h"
#import "UIImage+Blur.h"
#import "JCRBlurView.h"
#import "PTAlbumConstants.h"
#import "APRoundedButton.h"


static NSString *CellWithIdentifier = @"AlbumPhotoCell";

@interface PTASysAlbumVC (){
    BOOL isFirstLoading;
    JCRBlurView *coverView; //right part of cover view when album group shown
    
    UIImageView *navBackgroundImage;      //导航栏背景图片

    UIView *emptyAlbumView;                //相册为空时的提醒页面
    
}

@property (strong,nonatomic) UINib *sectionHeaderNib;

@property (nonatomic, assign) NSInteger maximumNumberOfSelection;  //相册列表中 Section 数目

@end

@implementation PTASysAlbumVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initVariable];
    
    [self.navTitle setText:@"系统相册"];
    [self.rightBtn setTitle:@"其他相册" forState:UIControlStateNormal];
    [self.rightBtn addTarget:self action:@selector(showRightViewController) forControlEvents:UIControlEventTouchUpInside];
    
    coverBlurImgViewAlpha = 0.1;
    isFirstLoading = YES;
    nColumnCount = 3;
    photoURLArray = [[NSMutableArray alloc]init];
    newDateArray = [[NSMutableArray alloc]init];
    dataMArr = [[NSMutableDictionary alloc] init];
    oldNumber = 0;
    
    [self initCollectionView];  //当前页面控件
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"系统相册"];
    
    //判断图片相册数据是否更新
    [MobClick beginLogPageView:@"AlbumView"];
    if (isFirstLoading) {
        isFirstLoading = NO;
    } else {
        [self readAlbumList];
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"系统相册"];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [MobClick beginLogPageView:@"PhotoGallaryPage"];
    [self performSelectorInBackground:@selector(readAlbumList) withObject:nil];
    //这里做相册为空处理
}

#pragma mark - 系统相册相关对象初始化

- (void)readAlbumList
{
    [ASSETHELPER getPhotoListOfGroupByIndex:0 result:^(NSArray *aPhotos) {
        if (![Util isNeedRefresh] && [aPhotos count] == oldNumber) {
            return ; //不用刷新
        }
        [self handlePhotoArrays:aPhotos];
    }];
}

#pragma mark - 把相册图片,显示到 CollectionView 的入口

-(void) handlePhotoArrays:(NSArray *)aPhotos {
    photoURLArray = [[NSMutableArray alloc]init];
    oldNumber = [aPhotos count];
    [Util setRefreshStatus:FALSE];
    
    NSMutableDictionary *dicImages= [[NSMutableDictionary alloc]init];
    if (aPhotos) {
        for (ALAsset *  assetPhotos in aPhotos) {
            //类型, Location , 时长,方向,日期,格式 , URL地址
            NSDate * nsALAssetPropertyDate = [ assetPhotos valueForProperty:ALAssetPropertyDate ] ;
            
            NSString * strDate = [NDDateTools stringFromDateToDay:nsALAssetPropertyDate];
            NSMutableArray *arrayGroup = [dicImages objectForKey:strDate];
            if (arrayGroup == nil) {
                arrayGroup = [[NSMutableArray alloc] init];
            }
            [arrayGroup addObject:assetPhotos];
            [dicImages setValue:arrayGroup forKey:strDate];
        }
    }
    
    dataMArr = dicImages;
    newDateArray = [[dataMArr allKeys] mutableCopy];
    [newDateArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSDate *date1 = [dateFormatter dateFromString:obj1];
        NSDate *date2 = [dateFormatter dateFromString:obj2];
        
        double a = date1.timeIntervalSince1970;
        double b = date2.timeIntervalSince1970;
        if (a < b) {
            return NSOrderedDescending;
        } else if (a > b) {
            return NSOrderedAscending;
        } else {
            return NSOrderedSame;
        }
    }];
    
    
    for (NSInteger i=0; i<[newDateArray count]; i++) {
        NSString *strDate =[newDateArray objectAtIndex:i];
        NSMutableArray *arrayGroup = [dicImages objectForKey:strDate];
        if (photoURLArray) {
            [photoURLArray addObjectsFromArray:arrayGroup];
        }
    }
    
    //相册加载完毕,关闭 滚动加载提示
    [self performSelectorOnMainThread:@selector(relayoutContentView) withObject:nil waitUntilDone:NO];
}

-(void) relayoutContentView {
    [self shutdownCurrentLoaderWithView:_cvPhotoList animated:YES];
    
    //相册加载完成,初始化导航栏右侧相册目录视图
    //右侧滑出相册列表
    picker = [[PTASysAssetGroupVC alloc] init];
    picker.view.frame = CGRectMake(0, KTopViewHeigh, Main_Screen_Width*0.7, Main_Screen_Height-KTopViewHeigh);
    picker.dele= self;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups=NO;
    _rightVC = picker;
    
    _rightSideView = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, KTopViewHeigh, picker.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:_rightSideView];
    [self initChildControllers:_rightVC];
    
    UIPanGestureRecognizer *_panGestureRec = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveViewWithGesture:)];
    [self.view addGestureRecognizer:_panGestureRec];
    
    
    //
    [_cvPhotoList reloadData];
    _cvPhotoList.contentOffset = CGPointMake(0, 0);
    // handle empty data
    if (oldNumber == 0) {
        UIFont *titleFont = [UIFont fontWithName:@"Avenir-Light" size:34];
        UIFont *infoFont = [UIFont fontWithName:@"Avenir-Light" size:18];
        
        emptyAlbumView = [[UIView alloc]initWithFrame:CGRectMake(0, KTopViewHeigh, Main_Screen_Width, Main_Screen_Height-KTopViewHeigh)];
        emptyAlbumView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:emptyAlbumView];
        
        UILabel *messageTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, Main_Screen_Width, 50)];
        [messageTitle setText:@"您还没有照片"];
        [messageTitle setFont:titleFont];
        [messageTitle setTextAlignment:NSTextAlignmentCenter];
        [messageTitle setTextColor:[UIColor colorWithHexString:@"#B1B1B1"]];
        messageTitle.backgroundColor = [UIColor clearColor];
        
        UILabel *messageInfo = [[UILabel alloc]initWithFrame:CGRectMake(0, messageTitle.frame.size.height+messageTitle.frame.origin.y, Main_Screen_Width, 30)];
        [messageInfo setText:@"开始使用相机记录您的生活吧"];
        [messageInfo setFont:infoFont];
        [messageInfo setTextAlignment:NSTextAlignmentCenter];
        [messageInfo setTextColor:[UIColor colorWithHexString:@"#747474"]];
        messageInfo.backgroundColor = [UIColor clearColor];
        
        CGFloat iconWH = 110;
        UIImage *cameraIcon = [UIImage imageNamed:@"photo_icon_photo2"];
        UIButton * btnCamera =  [UIButton buttonWithType:UIButtonTypeCustom];
        btnCamera.frame = CGRectMake((Main_Screen_Width-iconWH)/2, messageInfo.frame.origin.y+messageInfo.frame.size.height+30, iconWH, iconWH);
        [btnCamera setImage:cameraIcon forState:UIControlStateNormal];
        btnCamera.backgroundColor = [UIColor clearColor];
        [btnCamera addTarget:self action:@selector(openCamera) forControlEvents:UIControlEventTouchUpInside];
        
        [emptyAlbumView addSubview:messageTitle];
        [emptyAlbumView addSubview:messageInfo];
        [emptyAlbumView addSubview:btnCamera];
    }else if(emptyAlbumView){
        [emptyAlbumView removeFromSuperview];
    }
}
#pragma mark - for init
- (void)initCollectionView
{
    self.automaticallyAdjustsScrollViewInsets = false;
    _cvPhotoList = [[UITableView alloc] initWithFrame:CGRectMake(0, KTopViewHeigh, Main_Screen_Width, Main_Screen_Height-KTopViewHeigh-kBottomBarHeight)];
    [_cvPhotoList setBackgroundColor:KBackgroundColor];
    _cvPhotoList.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_cvPhotoList setDelegate:self];
    [_cvPhotoList setDataSource:self];
    [self.view addSubview:_cvPhotoList];
    
    [self startCurrentLoaderWithView:_cvPhotoList withTitle:@"相册读取中..." animated:YES];
    
    // 1.添加一个coverImgView,用于点击了右侧相册按钮时,
    //进行屏幕截图并加上毛玻璃效果,置于最上方作为蒙板
    _coverBlurImgView = [[UIImageView alloc]init];
    // 4.旋转完成之后,才可以得到真实的frame,暂时隐藏起来,当点击cell的时侯才展示  -5
    _coverBlurImgView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    _coverBlurImgView.alpha = coverBlurImgViewAlpha;
    _coverBlurImgView.hidden = YES;
    [self.view addSubview:_coverBlurImgView];
    [_cvPhotoList bringSubviewToFront:_coverBlurImgView];
}

#pragma mark - 代理方法

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

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [dataMArr count];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *values = [ dataMArr objectForKey:[newDateArray objectAtIndex:[indexPath section]]];
    CGFloat height = 0.0f;
    //第一个Section 单独处理
    NSInteger section = indexPath.section;
    if (section == 0) {
        NSInteger count = ([values count]+1)/4;
        height = (count+1)*HEIGHT_ALBUM_PHOTO+count*6;
        
        if (([values count]+1)%4==0) {
            height-=HEIGHT_ALBUM_PHOTO;
        }
    }
    else
    {
        NSInteger count = [values count]/4;
        height = (count+1)*HEIGHT_ALBUM_PHOTO+count*6;
        
        if ([values count]%4==0) {
            height-=HEIGHT_ALBUM_PHOTO;
        }
    }
    
    
    return height+10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DoPhotoCollectionViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellWithIdentifier];
    if (cell == nil) {
        cell = [[DoPhotoCollectionViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellWithIdentifier];
    }
    NSArray *values = [dataMArr objectForKey:[newDateArray objectAtIndex:indexPath.section]];
    [cell bindWithAssetArray:values withSection:[indexPath section] withRect:cell.frame  isSelected:NO withDelegate:self];   //选中某张照片
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

#pragma mark - UICollectionViewDelegates for photos
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 50)];
    headerView.backgroundColor=[UIColor clearColor];
    
    //替换
    UIView *circleView = [[UIView alloc]initWithFrame:CGRectMake(Main_Screen_Width*0.05, 10, 250, 30)];
    [circleView setBackgroundColor:[UIColor clearColor]];
    [headerView addSubview:circleView];
    
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormatter dateFromString:[newDateArray objectAtIndex:section]];
    
    
    NSDate *today = [NSDate date];
    NSString *strWeek = [NDDateTools getWeekdayFromNSDate:date];
    
    UIFont *myCustomFont1 = [UIFont fontWithName:@"Avenir-Light" size:22];
    UIFont *myCustomFont2 = [UIFont fontWithName:@"Avenir-Light" size:14];
    UIFont *myCustomFont3 = [UIFont fontWithName:@"Avenir-Light" size:16];
    
    int compare = [NDDateTools compareOneDay:today withAnotherDay:date];
    CGFloat topPadding = 10.0f;
    if (compare == 0) {
        UILabel *todayLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, topPadding, 50, 20)];
        todayLabel.text=  @"今天";
        todayLabel.font = myCustomFont1;
        todayLabel.backgroundColor = [UIColor clearColor];
        todayLabel.textAlignment = NSTextAlignmentLeft;
        todayLabel.textColor=RGBCOLOR(98, 98, 98);
        [circleView addSubview:todayLabel];
        
        UILabel *dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(todayLabel.frame.size.width, topPadding+5, 80, 20)];
        NSString *strDay1 = [dateFormatter stringFromDate:date];
        dayLabel.text=  strDay1;
        dayLabel.font = myCustomFont2;
        dayLabel.backgroundColor = [UIColor clearColor];
        dayLabel.textAlignment = NSTextAlignmentCenter;
        dayLabel.textColor=RGBCOLOR(137, 137, 137);
        [circleView addSubview:dayLabel];
        
        UILabel *weekDayLabel = [[UILabel alloc] initWithFrame:CGRectMake(todayLabel.frame.size.width+dayLabel.frame.size.width, topPadding+5, 50, 20)];
        weekDayLabel.text= [NSString stringWithFormat:@"(%@)",strWeek];
        weekDayLabel.font = myCustomFont2;
        weekDayLabel.backgroundColor = [UIColor clearColor];
        weekDayLabel.textColor=RGBCOLOR(137, 137, 137);
        weekDayLabel.textAlignment = NSTextAlignmentCenter;
        [circleView addSubview:weekDayLabel];
    }else{
        
        UILabel *dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,topPadding, 120, 20)];
        NSString *strDay = [dateFormatter stringFromDate:date];
        dayLabel.text=  strDay;
        dayLabel.font = myCustomFont1;
        dayLabel.backgroundColor = [UIColor clearColor];
        dayLabel.textAlignment = NSTextAlignmentLeft;
        dayLabel.textColor=RGBCOLOR(98, 98, 98);
        [circleView addSubview:dayLabel];
        
        UILabel *weekDayLabel = [[UILabel alloc] initWithFrame:CGRectMake(dayLabel.frame.size.width,topPadding, 50, 25)];
        weekDayLabel.text= [NSString stringWithFormat:@"(%@)",strWeek];
        weekDayLabel.font = myCustomFont3;
        weekDayLabel.backgroundColor = [UIColor clearColor];
        weekDayLabel.textColor=RGBCOLOR(137, 137, 137);
        weekDayLabel.textAlignment = NSTextAlignmentLeft;
        [circleView addSubview:weekDayLabel];
    }
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50.0;
}


//去掉UItableview headerview黏性(sticky)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 50;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

#pragma mark -  DoPhotoCollectionViewCell
-(void) itemClickedWithIndex:(NSInteger) index withSection:(NSInteger)section{
    NSLog(@"------indexSection:%ld ,tagIndex : %ld",(long)section,(long)index);
    NSInteger allValue = 0; //从0开始,总的图片下标
    
    if (index == 999999999) {
        //跳转到拍照
        [self openCamera];
    }else{
        
        for (int i=0; i<[newDateArray count]; i++) {
            if(section == i){
                allValue += index;
                break;
            }else if(section > i){
                NSString  *key = [newDateArray objectAtIndex:i];
                NSArray *sectionValues = [dataMArr objectForKey:key];
                NSInteger valuesCount = [sectionValues count];
                allValue += valuesCount;
            }
        }
    
        //取出相册中,选中的照片
        UIImage *currentImage = [self configItemImageWithIndex:allValue];
        
        
    }
}



-(void) openCamera{
    /*
    PTPaiPaiSimpleCameraViewController *cameraVC = [[PTPaiPaiSimpleCameraViewController alloc] init];
    cameraVC.simpleCameraDelegate = self;
    [self.navigationController pushViewController:cameraVC animated:YES];
     */
}


#pragma mark -  从相册取出指定 index 的相片
- (UIImage*) configItemImageWithIndex:(NSInteger)index{
    if (index<0 || index>[photoURLArray count]-1) {
        return nil;
    }
    UIImage *imgFull;
    //取出相册中指定索引的图片
    imgFull= [ASSETHELPER getImageFromAsset:[photoURLArray objectAtIndex:index] type:ASSET_PHOTO_SCREEN_SIZE];
    
    return imgFull;
}

@end

自定义单元格

@protocol PhotoAlbumClickedDelegate <NSObject>

-(void) itemClickedWithIndex:(NSInteger) index withSection:(NSInteger)section;

@end


@interface DoPhotoCollectionViewCell : UITableViewCell {
    NSMutableArray *arrPhotos;
    id<PhotoAlbumClickedDelegate> delegate;

    NSInteger section0Count;                     //默认第一个Section 中照片数目
    
    NSArray * albumAllPhotosAsset;               //保存相册所有图片的数组
    
}

@property (nonatomic,assign)NSInteger section;     //TableView Section Number

//初始化整个 tableView Cell
-(void) bindWithAssetArray:(NSArray *) arrayAsset withSection:(NSInteger) intSection withRect:(CGRect)rect isSelected:(BOOL)isSeled withDelegate:(id<PhotoAlbumClickedDelegate>)del;

@end
//
//  DoPhotoCollectionViewCell.m
//  PTAlbum
//
//  Created by LiLiLiu on 15/4/24.
//  Copyright (c) 2015年 putao.Inc. All rights reserved.
//

#import "DoPhotoCollectionViewCell.h"

#import "ASSETHELPER.h"
#import "UIColor+Help.h"
#import "PTAlbumConstants.h"
#import "UzysAppearanceConfig.h"           //复选配置

@implementation DoPhotoCollectionViewCell

static UIImage *checkedIcon;              //选中的 icon
static UIImage *uncheckedIcon;            //未选中的 icon
static UIColor *selectedColor;            //选中缩略图的背景颜色


+ (void)initialize
{
    UzysAppearanceConfig *appearanceConfig = [UzysAppearanceConfig sharedConfig];
    
    checkedIcon     = [UIImage imageNamed:appearanceConfig.assetSelectedImageName];
    uncheckedIcon   = [UIImage imageNamed:appearanceConfig.assetDeselectedImageName];
    selectedColor   = [UIColor colorWithWhite:1 alpha:0.3];
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self){
        arrPhotos = [[NSMutableArray alloc] init];
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}


#pragma mark -  单击某张图片,调用代理方法
- (void) handleImageTap:(UITapGestureRecognizer *) gestureRecognizer{
    //根据选中的 item ,获取当前表格中的 tableCell 以及 section  row
// 从 stackoverflow 上面找的方法,获取当前所点击的 view 在 UITableContentView 中的位置
UIView *parentCell = gestureRecognizer.view.superview; while (![parentCell isKindOfClass:[UITableViewCell class]]) { //iOS 7 onwards the table cell hierachy has changed. parentCell = parentCell.superview; } UIView *parentView = parentCell.superview; while (![parentView isKindOfClass:[UITableView class]]) { // iOS 7 onwards the table cell hierachy has changed. parentView = parentView.superview; } UITableView *tableView = (UITableView *)parentView; NSIndexPath *indexPath = [tableView indexPathForCell:(UITableViewCell *)parentCell]; // // 能够获取正确的 section , row 永远为 0 // if (albumAllPhotosAsset) { NSInteger tag = gestureRecognizer.view.tag; //把选中 item 的 section tag 保存在数组中,实现多选 // 修改选择图标 [self updatePhotoItemSelectedIconWithSection:indexPath.section withIndex:tag isSelected:YES]; //调用代理方法处理被选中事件 [delegate itemClickedWithIndex:tag withSection:self.section]; } } -(void) bindWithAssetArray:(NSArray *) arrayAsset withSection:(NSInteger) intSection withRect:(CGRect)rect isSelected:(BOOL)isSeled withDelegate:(id<PhotoAlbumClickedDelegate>)del{ albumAllPhotosAsset = arrayAsset; delegate = del; self.section = intSection; ALAsset * assetPhotos; for (UIImageView *view in arrPhotos) { [view removeFromSuperview]; } [arrPhotos removeAllObjects]; //BOOL isSelected = self.selected; // 增加一个跳转到相机 图标 if (self.section == 0) { section0Count = [arrayAsset count]; for(NSInteger i=0;i<=[arrayAsset count];i++){ UIImageView *selectIcon; //每张图片右下角的多选图标 UIImageView *_ivPhoto; //每次循环创建一个 UIImageView int originX = (i%NUM_ROW_PHOTO)*HEIGHT_ALBUM_PHOTO+6*(i%NUM_ROW_PHOTO); int originY = HEIGHT_ALBUM_PHOTO*(i/NUM_ROW_PHOTO)+6*(i/NUM_ROW_PHOTO); // //显示的缩略图 // _ivPhoto = [[UIImageView alloc] initWithFrame:CGRectMake(originX, originY,HEIGHT_ALBUM_PHOTO, HEIGHT_ALBUM_PHOTO)]; _ivPhoto.contentMode = UIViewContentModeScaleAspectFill; _ivPhoto.userInteractionEnabled = TRUE; // //缩略图上面显示的 选中图标 // //-------------照片右下角的多选Icon-------------- CGFloat iconWH = HEIGHT_ALBUM_PHOTO*0.5; selectIcon = [[UIImageView alloc]initWithFrame:CGRectMake(HEIGHT_ALBUM_PHOTO-iconWH, HEIGHT_ALBUM_PHOTO-iconWH, iconWH, iconWH)]; if (i<[arrayAsset count]) { assetPhotos = (ALAsset *)[arrayAsset objectAtIndex:i]; UIImage *image = [ASSETHELPER getImageFromAsset:assetPhotos type:ASSET_PHOTO_THUMBNAIL]; _ivPhoto.tag = i; _ivPhoto.image =image; //-------------------添加选择icon------------------------ if (isSeled) { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, selectedColor.CGColor); CGContextFillRect(context, rect); [selectIcon setImage:[UIImage imageNamed:@"album_button_choose"]]; } else { [selectIcon setImage:[UIImage imageNamed:@"album_button_choose2"]]; } } if (i==[arrayAsset count]) { //创建 UIImage UIImage *camreaIcon = [UIImage imageNamed:@"album_button_photo"]; _ivPhoto.tag = 999999999; //创建 UIImageView _ivPhoto.backgroundColor = [UIColor colorWithHexString:@"#eae7e2"]; _ivPhoto.image = camreaIcon; } [self.contentView addSubview:_ivPhoto]; [_ivPhoto addSubview:selectIcon]; [arrPhotos addObject:_ivPhoto]; UITapGestureRecognizer *smallImageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)]; [smallImageTap setNumberOfTapsRequired:1]; [_ivPhoto addGestureRecognizer:smallImageTap]; } }else{ for(NSInteger i=0;i<[arrayAsset count];i++){ UIImageView *selectIcon; //每张图片右下角的多选图标 assetPhotos = (ALAsset *)[arrayAsset objectAtIndex:i]; UIImage *image = [ASSETHELPER getImageFromAsset:assetPhotos type:ASSET_PHOTO_THUMBNAIL]; //int originX = (i%NUM_ROW_PHOTO)*HEIGHT_ALBUM_PHOTO+6*(i%NUM_ROW_PHOTO)+65; int originX = (i%NUM_ROW_PHOTO)*HEIGHT_ALBUM_PHOTO+6*(i%NUM_ROW_PHOTO); int originY = HEIGHT_ALBUM_PHOTO*(i/NUM_ROW_PHOTO)+6*(i/NUM_ROW_PHOTO); UIImageView *_ivPhoto = [[UIImageView alloc] initWithFrame:CGRectMake(originX, originY,HEIGHT_ALBUM_PHOTO, HEIGHT_ALBUM_PHOTO)]; _ivPhoto.contentMode = UIViewContentModeScaleAspectFill; _ivPhoto.tag = i; _ivPhoto.userInteractionEnabled = TRUE; _ivPhoto.image =image; // //缩略图上面显示的 选中图标 // //-------------照片右下角的多选Icon-------------- CGFloat iconWH = HEIGHT_ALBUM_PHOTO*0.5; selectIcon = [[UIImageView alloc]initWithFrame:CGRectMake(HEIGHT_ALBUM_PHOTO-iconWH, HEIGHT_ALBUM_PHOTO-iconWH, iconWH, iconWH)]; //-------------------添加选择icon------------------------ if (isSeled) { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, selectedColor.CGColor); CGContextFillRect(context, rect); [selectIcon setImage:[UIImage imageNamed:@"album_button_choose"]]; } else { [selectIcon setImage:[UIImage imageNamed:@"album_button_choose2"]]; } [_ivPhoto addSubview:selectIcon]; [self.contentView addSubview:_ivPhoto]; [arrPhotos addObject:_ivPhoto]; UITapGestureRecognizer *smallImageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)]; [smallImageTap setNumberOfTapsRequired:1]; [_ivPhoto addGestureRecognizer:smallImageTap]; } } } - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); CGContextFillRect(context, rect); //下分割线 CGColorRef lineBottomColor = RGBCOLOR(217, 217, 217).CGColor; CGContextSetStrokeColorWithColor(context, lineBottomColor); CGContextStrokeRect(context, CGRectMake(10, rect.size.height, rect.size.width - 20, 2)); } #pragma mark - private Method -(void) updatePhotoItemSelectedIconWithSection:(NSInteger) intSection withIndex:(NSInteger)intIndex isSelected:(BOOL)isSeled{ ALAsset * assetPhotos; for (UIImageView *view in arrPhotos) { [view removeFromSuperview]; } [arrPhotos removeAllObjects]; //BOOL isSelected = self.selected; // 增加一个跳转到相机 图标 if (self.section == 0) { section0Count = [albumAllPhotosAsset count]; for(NSInteger i=0;i<=[albumAllPhotosAsset count];i++){ UIImageView *selectIcon; //每张图片右下角的多选图标 UIImageView *_ivPhoto; //每次循环创建一个 UIImageView int originX = (i%NUM_ROW_PHOTO)*HEIGHT_ALBUM_PHOTO+6*(i%NUM_ROW_PHOTO); int originY = HEIGHT_ALBUM_PHOTO*(i/NUM_ROW_PHOTO)+6*(i/NUM_ROW_PHOTO); // //显示的缩略图 // _ivPhoto = [[UIImageView alloc] initWithFrame:CGRectMake(originX, originY,HEIGHT_ALBUM_PHOTO, HEIGHT_ALBUM_PHOTO)]; _ivPhoto.contentMode = UIViewContentModeScaleAspectFill; _ivPhoto.userInteractionEnabled = TRUE; // //缩略图上面显示的 选中图标 // //-------------照片右下角的多选Icon-------------- CGFloat iconWH = HEIGHT_ALBUM_PHOTO*0.5; selectIcon = [[UIImageView alloc]initWithFrame:CGRectMake(HEIGHT_ALBUM_PHOTO-iconWH, HEIGHT_ALBUM_PHOTO-iconWH, iconWH, iconWH)]; if (i<[albumAllPhotosAsset count]) { assetPhotos = (ALAsset *)[albumAllPhotosAsset objectAtIndex:i]; UIImage *image = [ASSETHELPER getImageFromAsset:assetPhotos type:ASSET_PHOTO_THUMBNAIL]; _ivPhoto.tag = i; _ivPhoto.image =image; //-------------------添加选择icon------------------------ if (intIndex == i) { [selectIcon setImage:[UIImage imageNamed:@"album_button_choose"]]; } else { [selectIcon setImage:[UIImage imageNamed:@"album_button_choose2"]]; } } if (i==[albumAllPhotosAsset count]) { //创建 UIImage UIImage *camreaIcon = [UIImage imageNamed:@"album_button_photo"]; _ivPhoto.tag = 999999999; //创建 UIImageView _ivPhoto.backgroundColor = [UIColor colorWithHexString:@"#eae7e2"]; _ivPhoto.image = camreaIcon; } [self.contentView addSubview:_ivPhoto]; [_ivPhoto addSubview:selectIcon]; [arrPhotos addObject:_ivPhoto]; UITapGestureRecognizer *smallImageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)]; [smallImageTap setNumberOfTapsRequired:1]; [_ivPhoto addGestureRecognizer:smallImageTap]; } }else{ for(NSInteger i=0;i<[albumAllPhotosAsset count];i++){ UIImageView *selectIcon; //每张图片右下角的多选图标 assetPhotos = (ALAsset *)[albumAllPhotosAsset objectAtIndex:i]; UIImage *image = [ASSETHELPER getImageFromAsset:assetPhotos type:ASSET_PHOTO_THUMBNAIL]; //int originX = (i%NUM_ROW_PHOTO)*HEIGHT_ALBUM_PHOTO+6*(i%NUM_ROW_PHOTO)+65; int originX = (i%NUM_ROW_PHOTO)*HEIGHT_ALBUM_PHOTO+6*(i%NUM_ROW_PHOTO); int originY = HEIGHT_ALBUM_PHOTO*(i/NUM_ROW_PHOTO)+6*(i/NUM_ROW_PHOTO); UIImageView *_ivPhoto = [[UIImageView alloc] initWithFrame:CGRectMake(originX, originY,HEIGHT_ALBUM_PHOTO, HEIGHT_ALBUM_PHOTO)]; _ivPhoto.contentMode = UIViewContentModeScaleAspectFill; _ivPhoto.tag = i; _ivPhoto.userInteractionEnabled = TRUE; _ivPhoto.image =image; // //缩略图上面显示的 选中图标 // //-------------照片右下角的多选Icon-------------- CGFloat iconWH = HEIGHT_ALBUM_PHOTO*0.5; selectIcon = [[UIImageView alloc]initWithFrame:CGRectMake(HEIGHT_ALBUM_PHOTO-iconWH, HEIGHT_ALBUM_PHOTO-iconWH, iconWH, iconWH)]; //-------------------添加选择icon------------------------ if (intIndex == i) { [selectIcon setImage:[UIImage imageNamed:@"album_button_choose"]]; } else { [selectIcon setImage:[UIImage imageNamed:@"album_button_choose2"]]; } [_ivPhoto addSubview:selectIcon]; [self.contentView addSubview:_ivPhoto]; [arrPhotos addObject:_ivPhoto]; UITapGestureRecognizer *smallImageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)]; [smallImageTap setNumberOfTapsRequired:1]; [_ivPhoto addGestureRecognizer:smallImageTap]; } } } @end


原文地址:https://www.cnblogs.com/allanliu/p/4460859.html