UICollectionView的基本使用

如果你對UICollectionView并不熟悉,可以參考我的這篇文章

UICollectionView相信大家肯定不陌生了,類型和tableView很相似,但他比后者實力更為強大,之前很少寫UICollectionView,抽個時間找了些例子,并自己寫了個demo,作了個總結,現在記錄一下基本用法,一方面便于自己遺忘查詢,另一方面也希望幫到和我一樣很少用到這種方法的童鞋。

遵循代理

UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout

定義兩個屬性,分別是UICollectionView和數據源數組

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *arr;

cellID的定義,在這里是要注冊cellID的,tableview中可以在cellforrow方法里面直接static 一個cellid,在這里不行。

// 注意const的位置
static NSString *const cellId = @"cellId";
static NSString *const headerId = @"headerId";
static NSString *const footerId = @"footerId";

基本方法

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self arr];
    [self collectionView];
    
}

- (NSMutableArray *)arr {
    if (_arr == nil) {
        _arr = [[NSMutableArray alloc] initWithObjects:@"123",@"234",@"345",@"456",@"567",nil];
    }
    return _arr;
}

- (UICollectionView *)collectionView {

    if (!_collectionView) {

        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        _collectionView = [[ UICollectionView alloc ] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 160) collectionViewLayout :layout];
        
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor grayColor];
        [_collectionView registerClass :[ UICollectionViewCell class ] forCellWithReuseIdentifier : cellId ];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerId];
        
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}

三個代理的代理方法,注釋寫在代碼里了,有需要了解的小伙伴可以一步一步看

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _arr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
    UIButton * btn = [[UIButton alloc]initWithFrame:cell.bounds];
    [btn setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    btn.backgroundColor = [UIColor yellowColor];
    [btn setTitle:[_arr objectAtIndex:indexPath.row]  forState:(UIControlStateNormal)];
    [cell.contentView addSubview:btn];
    btn.userInteractionEnabled = NO;
    UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(press:)];
    btn.userInteractionEnabled = YES;
    [btn addGestureRecognizer:press];
    
//    UICollectionViewCell *cell = [_collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor purpleColor];
    
    
    return cell;
    
}

- (void)press:(UILongPressGestureRecognizer *)press {
    if (press.state == UIGestureRecognizerStateBegan) {
        NSLog(@"qwe");
    } 
}

// 和UITableView類似,UICollectionView也可設置段頭段尾
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *headerView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerId forIndexPath:indexPath];
        if (!headerView) {
            headerView = [[UICollectionReusableView alloc] init];
        }
        headerView.backgroundColor = [UIColor yellowColor];
        return headerView;
    }
    else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        UICollectionReusableView *footerView = [_collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:footerId forIndexPath:indexPath];
        if (!footerView) {
            footerView = [[UICollectionReusableView alloc] init];
        }
        footerView.backgroundColor = [UIColor lightGrayColor];
        return footerView;
    }
    return nil;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath
{
    
}

#pragma mark -- UICollectionViewDelegateFlowLayout
//定義每個item 的大小
- ( CGSize )collectionView:( UICollectionView *)collectionView layout:( UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:( NSIndexPath *)indexPath{
    return CGSizeMake ( 70 , 20 );
}

//定義邊界item 的邊距(次序: 上,左,下,右邊)
-( UIEdgeInsets )collectionView:( UICollectionView *)collectionView layout:( UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:( NSInteger )section{
    return UIEdgeInsetsMake ( 10 , 10 , 10 , 10 );//最上面item距離上部10,最左邊距離最左邊邊界10,其他也是這個意思,不清楚可以自己試試
}

//每個section中不同的行之間的行間距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 20;
}

//每個item之間的間距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 15;
}

//返回頭headerView的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    CGSize size={320,45};
    return size;
}

//返回尾footerView的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    CGSize size={320,45};
    return size;
}

#pragma mark ---- UICollectionViewDelegate

//設置是否讓item高亮(有時候我們點擊item,讓他變色,這里設置no是不會發(fā)生改變的)
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

// 點擊高亮
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor greenColor];
}

// 選中某item
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"選中了~~~");
}

// 長按某item,彈出copy和paste的菜單(以下三個方法要一起實現,這是實現copy和paste的,可以點進去看看蘋果的注釋)
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return NO; //在這里,為了實現自定義長按手勢效應,我把這里長按彈出粘貼復制給禁用了,如果想看到效果,把上面collectionView的懶加載那里添加手勢給去了,然后這里置為YES
    
}

// 使copy和paste有效
- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender
{
    if ([NSStringFromSelector(action) isEqualToString:@"copy:"] || [NSStringFromSelector(action) isEqualToString:@"paste:"])
    {
        return YES;
    }
    
    return NO;
}

//執(zhí)行對應操作
- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender
{
    if([NSStringFromSelector(action) isEqualToString:@"copy:"])
    {
        NSLog(@"-------------執(zhí)行拷貝-------------");
        //點擊長按彈出copy和paste--點擊copy刪除cell
        __weak typeof(self)weakSelf = self;
        [_collectionView performBatchUpdates:^{
            [weakSelf.arr removeObjectAtIndex:indexPath.row];
            [weakSelf.collectionView deleteItemsAtIndexPaths:@[indexPath]];
            //刪除后再計算collection的高度

            weakSelf.collectionView.frame = CGRectMake(0, 64, self.view.frame.size.width, 160);
            
        } completion:nil];
    }
    else if([NSStringFromSelector(action) isEqualToString:@"paste:"])
    {
        NSLog(@"-------------執(zhí)行粘貼-------------");
        //點擊長按彈出copy和paste--點擊paste添加一個cell
        __weak typeof(self)weakSelf = self;
        [_collectionView performBatchUpdates:^{
            // 構造一個indexPath
            NSIndexPath *indePath = [NSIndexPath indexPathForItem:weakSelf.arr.count inSection:0];
            [weakSelf.collectionView insertItemsAtIndexPaths:@[indePath]]; // 然后在此indexPath處插入給collectionView插入一個item
            [weakSelf.arr addObject:@"110"]; // 保持collectionView的item和數據源一致
            //增加后再計算collection的高度

            weakSelf.collectionView.frame = CGRectMake(0, 64, self.view.frame.size.width, 160);
            
        } completion:nil];
    }
}

如果對您起到了幫助,就給我點個贊吧

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容