2012-10-30 316 views
12

这是我第一次创建UICollectionView。这是我希望它看起来像:在UICollectionView中设置边框

enter image description here

我读了一些教程,我知道它是怎么工作的。就像你在图像中看到的那样,UICollection单元格有从上,下,左,右的边界。你知道如何在Collection View中设置这些边框吗?

正如您所看到的,其中两个项目是通过红色选择的。 UICollectionView有可能有多个选定的项目吗?如果是的话,你可以给我一些教程。

回答

26

小例子项目位置: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 

其结果是这样的:

iPhone screen shot

克隆与the sample project玩。

在你想跟踪哪些用户在视图控制器已经选择了一个真实的项目,通过对UICollectionViewDelegate协议– collectionView:didSelectItemAtIndexPath:方法将所选择的数据模型实体的一些结构(如NSMutableArray)。

+0

我赞赏你的完整答案。 – Ali