表格选中效果展示
源代码地址:https://github.com/EizoiOS/ImagePickerClass
效果图如下:
在单元格上增加一张图片,此处的实例是把背景阴影也一起做为一张图片,平时可以通过一个VIEW来设置它的透明度;还要单元格给它赋于相应的点击事件;
1:此为单元格视图,用于处理选中的效果
EiaoAsset.h文件
@interface EizoAsset : UIView{ UIImageView * selectedView; // 创建一个ImageView -- 用来添加到选中的这个图片上 BOOL selected; // 创建一个bool值 -- 用来标识有无选中 } @property (strong,nonatomic)ALAsset * asset; // 通过ALAsset获得相应的资源 @property (assign , nonatomic) id parent; -(id)initWithAsset:(ALAsset*)asset; -(BOOL)selected; -(void)toggleSelection; @end
EiaoAsset.m文件: #import "EizoAsset.h" @interface EizoAsset(){ UIImageView * assetImageView; // 展示这个每一张图片的ImageView } @end @implementation EizoAsset -(id)initWithAsset:(ALAsset *)asset { if (self = [super initWithFrame:CGRectMake(0, 0, 0, 0)]) { self.asset = asset; assetImageView = [[UIImageView alloc]init]; assetImageView.contentMode = UIViewContentModeScaleAspectFill; assetImageView.image = [UIImage imageWithCGImage:[self.asset thumbnail]]; // ALAsset的thumbnail是图片的缩略图 [self addSubview:assetImageView]; selectedView = [[UIImageView alloc]init]; selectedView.image = [UIImage imageNamed:@"Select.png"]; selectedView.hidden = YES; [self addSubview:selectedView]; } return self; } - (BOOL)selected { return !selectedView.hidden; } -(void)setSelected:(BOOL)_selected { [selectedView setHidden:!_selected]; } // 在单元格 也就是上一个层面添加了一个手势 点击变化选中的状态 也就是改变这个bool值 - (void)toggleSelection { selectedView.hidden = !selectedView.hidden; } -(void)setFrame:(CGRect)frame { [super setFrame:frame]; assetImageView.frame = self.bounds; selectedView.frame = self.bounds; } @end
注意:这边已经把选中的效果去加上去,只是让它先隐藏起来,还设置它点击触发的事件;ALAsset就是数据模型,用来存一些图片的数据;
2:单元格文件:
eiaoAssetCell.h文件
#import <UIKit/UIKit.h> #define topMargin 5 @interface EizoAssetCell : UITableViewCell // 单元格的创建方法 -(instancetype)initWithAssets:(NSArray *)assets reuseIdentifier:(NSString *)identifier; // 传入这个assets的方法 -(void)setAssets:(NSArray *)assets; // @property (nonatomic,retain) NSArray * linesAssets; // 传入的图片的数组 -- 应该是所有的图片 @end eiaoAssetCell.m 文件: #import "EizoAssetCell.h" #import "EizoAsset.h" @implementation EizoAssetCell -(instancetype)initWithAssets:(NSArray *)assets reuseIdentifier:(NSString *)identifier { if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]) { self.linesAssets = assets; } return self; } -(void)layoutSubviews { CGFloat h = self.bounds.size.height - topMargin; CGFloat margin = (self.bounds.size.width - 4 * h) / 5.0; CGRect frame = CGRectMake(margin,topMargin, h, h); for(EizoAsset * eizoAsset in self.linesAssets) { eizoAsset.frame = frame; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:eizoAsset action:@selector(toggleSelection)]; [eizoAsset addGestureRecognizer:tap]; [self addSubview:eizoAsset]; frame.origin.x = frame.origin.x + frame.size.width + margin; } } @end
注意:这边最为重要的是在layoutSubviews里面的代码,UITapGestureRecognizer把target指向上面创建的EizoAsset视图,这样便可以调用上面创建的选中及反选的事件;