nhỏ ví dụ dự án ở đây: https://github.com/erikt/ETMultiSelect
Trước tiên, bạn phải làm cho nó có thể chọn nhiều hơn một ô trong UICollectionView
. Điều này được thực hiện bằng cách đặt thuộc tính allowsMultipleSelection
thành YES
trên chế độ xem bộ sưu tập.
Bộ điều khiển xem sẽ giống như thế này:
#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
Các UICollectionViewCell
được tạo thành từ một số quan điểm. Nó có chế độ xem nội dung, chế độ xem nền và chế độ xem nền đã chọn.
Có rất nhiều cách để đạt được một cái gì đó tương tự như hình ảnh của bạn, nhưng tôi thiết lập biên giới trên lớp nền được lựa chọn và thêm một subview vào xem nội dung đó là inset nên biên giới nền có thể nhìn thấy:
#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
kết quả là một cái gì đó như thế này:
Clone và chơi với the sample project.
Trong dự án thực, bạn muốn theo dõi những gì người dùng đã chọn trong trình điều khiển chế độ xem, bằng cách thêm các thực thể mô hình dữ liệu đã chọn vào một cấu trúc nào đó (như NSMutableArray
) theo phương thức – collectionView:didSelectItemAtIndexPath:
trên giao thức UICollectionViewDelegate
.
Nguồn
2012-11-04 00:09:06
Tôi đánh giá cao câu trả lời hoàn chỉnh của bạn. – Ali