ここの小さなサンプル プロジェクト: https://github.com/erikt/ETMultiSelect
まず、 で複数のセルを選択できるようにする必要がありますUICollectionView
。これを行うには、コレクション ビューでallowsMultipleSelection
プロパティをに設定します。YES
ビューコントローラーは次のようになります。
#import "ETViewController.h"
#import "ETCellView.h"
@implementation ETViewController
static NSString *cellIdentifier = @"cvCell";
- (void)viewDidLoad {
[super viewDidLoad];
// Register our custom collection view cell
[self.collectionView registerClass:ETCellView.class forCellWithReuseIdentifier:cellIdentifier];
// Make it possible to select multiple cells
self.collectionView.allowsMultipleSelection = YES;
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 10;
}
#pragma mark - UICollectionViewDelegate
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
ETCellView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
return cell;
}
@end
はUICollectionViewCell
いくつかのビューで構成されています。コンテンツ ビュー、背景ビュー、および選択された背景ビューがあります。
写真に似たものを実現する方法はたくさんありますが、選択した背景レイヤーに境界線を設定し、挿入されたコンテンツ ビューにサブビューを追加して、背景の境界線が見えるようにします。
#import "ETCellView.h"
#import <QuartzCore/QuartzCore.h>
@implementation ETCellView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.restorationIdentifier = @"cvCell";
self.backgroundColor = [UIColor clearColor];
self.autoresizingMask = UIViewAutoresizingNone;
CGFloat borderWidth = 3.0f;
UIView *bgView = [[UIView alloc] initWithFrame:frame];
bgView.layer.borderColor = [UIColor redColor].CGColor;
bgView.layer.borderWidth = borderWidth;
self.selectedBackgroundView = bgView;
CGRect myContentRect = CGRectInset(self.contentView.bounds, borderWidth, borderWidth);
UIView *myContentView = [[UIView alloc] initWithFrame:myContentRect];
myContentView.backgroundColor = [UIColor whiteColor];
myContentView.layer.borderColor = [UIColor colorWithWhite:0.5f alpha:1.0f].CGColor;
myContentView.layer.borderWidth = borderWidth;
[self.contentView addSubview:myContentView];
}
return self;
}
@end
結果は次のようになります。

サンプル プロジェクトを複製して再生します。
実際のプロジェクトでは、選択したデータ モデル エンティティをプロトコルのメソッドの構造体 ( などNSMutableArray
) に追加することで、View Controller でユーザーが選択したものを追跡する必要があります。– collectionView:didSelectItemAtIndexPath:
UICollectionViewDelegate