这个就相当于,我们上传照片时,进行照片的选择,选中的时候,上面会有一个小对勾,再次点击也就是取消时,对勾会消失
还是先看看效果图吧
emm就这样看吧,可以看到,选中的是最底下中间那张(少年气的萨沙)然后进行多选
然后取消几张图
ok,然后我们先看看代码
(这个应该有很多种方法,目前我用的是这一种,才疏学浅,还望大佬指教)
- 首先用到的是,UICollectionView控件
和tableview一样,自定义cell
创建一个cell文件
在.h文件中写上属性,例如这个,我写的是,photoImageView和photoButton两个属性
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface PhotoCollectionViewCell : UICollectionViewCell
@property UIImageView *photoImageView;
@property UIButton *photoButton;
@end
NS_ASSUME_NONNULL_END
然后在.m文件中
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
self.photoImageView = [[UIImageView alloc] init];
[self.contentView addSubview:_photoImageView];
self.photoButton = [[UIButton alloc] init];
[self.contentView addSubview:_photoButton];
return self;
}
- (void)layoutSubviews {
//两个属性的位置一样,emm是因为我把button加在——photoImageView上,进行点击按钮来进行选择图片和取消
_photoButton.frame = CGRectMake(0, 0, 130, 150);
_photoImageView.frame = CGRectMake(0, 0, 130, 150);
_photoButton.backgroundColor = [UIColor colorWithWhite:0.01 alpha:0.01];
}
在要显示的ViewController中
//初始化collection并设置一些属性
_collectionView.backgroundColor = [UIColor whiteColor];
_layout.itemSize = CGSizeMake(130, 150);
_layout.minimumLineSpacing = 5;
_layout.minimumInteritemSpacing = 5;
[self.view addSubview:_collectionView];
[_collectionView registerClass:[PhotoCollectionViewCell class] forCellWithReuseIdentifier:@"Ccell"];
_collectionView.delegate = self;
_collectionView.dataSource = self;
//返回每一个区的item数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 15;
}
//返回区数,默认为1
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
_cell = [_collectionView dequeueReusableCellWithReuseIdentifier:@"Ccell" forIndexPath:indexPath];
_cell.photoButton.tag = 100 + indexPath.item;
//添加点击事件
[_cell.photoButton addTarget:self action:@selector(pressSelected :) forControlEvents:UIControlEventTouchUpInside];
_cell.photoButton.selected = YES; //设置photoButton的select值
_cell.photoImageView.image = [UIImage imageNamed:_imageNameArray[indexPath.item]];
return _cell;
}
//点击事件
-(void)pressSelected : (UIButton *) btn {
//根据btn不同的selected值,进行选中和取消操作
if (btn.selected == YES) {
UIImageView *imageView = [[UIImageView alloc]initWithImage: [UIImage imageNamed:@"my_button_pressed.png"]];
imageView.frame = CGRectMake(110, 0, 20, 20);
[btn addSubview:imageView];
btn.selected = NO;
_num = _num + 1;
} else {
[btn.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; //移除在btn上的所有子视图,用来去掉右上角的对勾
btn.selected = YES;
_num = _num - 1;
}
}
然后就可以了,在下才疏学浅,暂且就想到了这个办法,用来进行点击选中和取消