2012-10-30 157 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