在UICollectionView中设置边框

时间:2012-10-30 15:19:08

标签: iphone objective-c ios

这是我第一次想要创建一个UICollectionView。这就是我希望它的样子:

enter image description here

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

如您所见,其中两个项目是用红色选择的。是否可以在UICollectionView中有多个选定的项目?如果是的话,请你给我发一些教程。

1 个答案:

答案 0 :(得分: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

在实际项目中,您希望通过将所选数据模型实体添加到NSMutableArray中的某个结构(如– collectionView:didSelectItemAtIndexPath:)来跟踪用户在视图控制器中选择的内容UICollectionViewDelegate协议上的方法。