iOS-UICollectionView

简介

继承:UIScrollView : UIView : UIResponder : NSObject
协议:UIDynamicItem, UITraitEnvironment, UIAppearanceContainer, NSCoding, UICoordinateSpace, UIAppearance, NSObject

UICollectionView主要用于瀑布流,与tableView最大的不同是需要自定义cell

//.h文件
#import <UIKit/UIKit.h>
@interface MyCollectionViewCell : UICollectionViewCell
@property (strong, nonatomic) UILabel *label;
@end
//.m文件
#import "MyCollectionViewCell.h"
@implementation MyCollectionViewCell
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        _label = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 70, 30)];
        [self.contentView addSubview:_label];
    }
    return self;
}
@end

简单例子
在viewController中需实现三个协议:
UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout

//
//  KMCollectionViewController.m
//  collectionViewtest
//
//  Created by MJM on 11/17/15.
//  Copyright © 2015 MJM. All rights reserved.
//

#import "KMCollectionViewController.h"
#import "KMCollectionViewCell.h"

@interface KMCollectionViewController ()
{
    UICollectionView *mainCollectionView;
}

@end

@implementation KMCollectionViewController

static NSString * const reuseIdentifier = @"Cell";

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

    //1.初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //设置collectionView滚动方向,默认是 UICollectionViewScrollDirectionVertical
    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //设置headerView的尺寸大小
    layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 100);
    //该方法也可以设置itemSize
    layout.itemSize =CGSizeMake(110, 150);

    //2.初始化collectionView
    mainCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    [self.view addSubview:mainCollectionView];
    mainCollectionView.backgroundColor = [UIColor clearColor];

    //3.注册collectionViewCell类(KMCollectionViewCell为自己单独建的类
    //注意,此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
    [mainCollectionView registerClass:[KMCollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

    //注册headerView  此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致  均为reusableView
    [mainCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];

    //4.设置代理
    mainCollectionView.delegate = self;
    mainCollectionView.dataSource = self;
}

#pragma mark <UICollectionViewDataSource>
//section数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 3;
}
//每个section的item数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 2;
}
//配置cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

    // Configure the cell

    return cell;
}

#pragma mark <UICollectionViewDelegate>

/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment this method to specify if the specified item should be selected
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
*/

/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
    return NO;
}

- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {

}
*/

#pragma mark <UICollectionViewDelegateFlowLayout>
//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(90, 130);
}

//footer的size
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
//{
//    return CGSizeMake(10, 10);
//}

//header的size
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
//{
//    return CGSizeMake(10, 10);
//}

//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}


//通过设置SupplementaryViewOfKind 来设置头部或者底部的view,其中 ReuseIdentifier 的值必须和 注册是填写的一致,本例都为 “reusableView”
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView" forIndexPath:indexPath];
    headerView.backgroundColor =[UIColor grayColor];
    UILabel *label = [[UILabel alloc] initWithFrame:headerView.bounds];
    label.text = @"这是collectionView的头部";
    label.font = [UIFont systemFontOfSize:20];
    [headerView addSubview:label];
    return headerView;
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    KMCollectionViewCell *cell = (KMCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
//    NSString *msg = cell.label.text;
//    NSLog(@"%@",msg);
}


/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

详解

Collection Views and Layout Objects
collectionView中有一个很重要对象:layout object(所属类UICollectionViewLayout)它主要包括所有items的布局信息,相当于另一个数据源。一般在创建一个collectionView时就会给它指定一个layout object,但可以动态改变它,它存储collectionView的collectionViewLayout 属性中,设置这个属性会立即更新layout,而不会有任何动画,除非调用
setCollectionViewLayout:animated:completion:方法。另外可以通过手势改变layout object.

Creating Cells and Supplementary Views
注册相关类:
registerClass:forCellWithReuseIdentifier: registerNib:forCellWithReuseIdentifier:
创建:
dequeueReusableCellWithReuseIdentifier:forIndexPath:
获得cell;
dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: 获得 supplementary view
(其identifier要和注册时的相同)

Reordering Items Interactively
势然后更新其位置。UICollectionViewController类提供一个默认的手势识别器,把
installsStandardGestureForInteractiveMovement置为YES;

初始化
- initWithFrame:collectionViewLayout:

配置
代理:delegate属性
数据源:dataSource属性

其他可选属性:
背景视图backgroundView

创建cells
registerClass:forCellWithReuseIdentifier:
registerNib:forCellWithReuseIdentifier:
registerClass:forSupplementaryViewOfKind:withReuseIdentifier
registerNib:forSupplementaryViewOfKind:withReuseIdentifier:

dequeueReusableCellWithReuseIdentifier:forIndexPath:
dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:

改变Layout
属性collectionViewLayout
1.setCollectionViewLayout:animated:增添变化动画
2.setCollectionViewLayout:animated:completion:动画结束后需通知以完成所需功能
3.startInteractiveTransitionToCollectionViewLayout:completion:通过交互改变layout
4.finishInteractiveTransition结束交互
5.cancelInteractiveTransition废除交互

重载内容
reload
reloadSections重载特定section的内容
reloadItemsAtIndexPaths:重载特定一项的内容

获取collectionView的状态
numberOfSections 总的section数
numberOfItemsInSection: 每个section中item数
visibleCells 可视cell

编辑items
insertItemsAtIndexPaths: 插入
moveItemAtIndexPath:toIndexPath: 移动
deleteItemsAtIndexPaths: 删除

编辑sections
insertSections: 插入
moveSection:toSection: 移动
deleteSections: 删除

Reordering Items Interactively
beginInteractiveMovementForItemAtIndexPath: 置为YES后便允许移动item
updateInteractiveMovementTargetPosition更新item的位置
endInteractiveMovement结束交互动作
cancelInteractiveMovement取消交互动作

Managing the Selection
allowsSelection 是否允许选择
allowsMultipleSelection 是否允许多项选择

1.indexPathsForSelectedItems 返回所选项的index paths
2.selectItemAtIndexPath:animated:scrollPosition(最后一个参数见UICollectionViewScrollPosition)
3.deselectItemAtIndexPath:animated:取消选择

Managing Focus
remembersLastFocusedIndexPath 默认为NO

Locating Items and Views in the Collection View
1.indexPathForItemAtPoint: 返回在特点点处item的indexpath
2.indexPathsForVisibleItems 返回可视items数组
3.indexPathForCell: 返回特定cell的indexpath
4.cellForItemAtIndexPath: 返回特定indexpath的可视cell(如果该cell不可视,则返回nil )
5.indexPathsForVisibleSupplementaryElementsOfKind:
返回所有特定类型的supplementary views的index paths(类型在layout object中定义的)
6.supplementaryViewForElementKind:atIndexPath: 返回特定indexpath 的supplementary view
7.visibleSupplementaryViewsOfKind: 返回特定类别的可视supplementary views数组

获取layout信息
layoutAttributesForItemAtIndexPath:
layoutAttributesForSupplementaryElementOfKind:atIndexPath:

Scrolling an Item Into View
scrollToItemAtIndexPath:atScrollPosition:animated: 跳转,直到特定的item可视

Animating Multiple Changes to the Collection View
(void)performBatchUpdates:(void (^)(void))updates
completion:(void (^)(BOOL finished))completion

Data Types
typedef void
(^UICollectionViewLayoutInteractiveTransitionCompletion)(BOOL completed, BOOL finish); collection view 交互结束后调用的块 ,completed 表示动画是否结束,finish表示过渡是否结束或取消,如果为NO,则安装旧layout

Constants
UICollectionViewScrollPosition

enum {
   UICollectionViewScrollPositionNone = 0,
   UICollectionViewScrollPositionTop = 1 << 0,
   UICollectionViewScrollPositionCenteredVertically = 1 << 1,
   UICollectionViewScrollPositionBottom = 1 << 2,

   UICollectionViewScrollPositionLeft = 1 << 3,
   UICollectionViewScrollPositionCenteredHorizontally = 1 << 4,
   UICollectionViewScrollPositionRight = 1 << 5
};
typedef NSUInteger UICollectionViewScrollPosition;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值