UI中CollectionView的創建與使用

在.h中聲明

@property (nonatomic, strong) UICollectionView *myCollecionView;



遵循CollectionView協議

<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>


.m文件中實現

@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    _collectionView.delegate = self;

    _collectionView.dataSource = self;

    

    

    //創建佈局對象

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

    

    //itmeitem之間的最小間距--默認是10

//    flowLayout.minimumInteritemSpacing = 110;

//    flowLayout.minimumLineSpacing = 100;

//    flowLayout.itemSize = CGSizeMake(80, 80);

    

//    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    

    

    //初始化CollectionView

    _myCollecionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 667 - 284, 375, 284) collectionViewLayout:flowLayout];

    _myCollecionView.tag = 200;

    _myCollecionView.delegate = self;

    _myCollecionView.dataSource = self;

    

    _myCollecionView.backgroundColor = [UIColor redColor];

    [self.view addSubview:_myCollecionView];

    

    

    //註冊單元格

    [_myCollecionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"myCollecionViewCell"];

    

    

}



#pragma mark -UICollectionViewDataSource

//指定組的個數

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    return 2;

}



//指定單元格的個數

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return 21;

}



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

{

    

    if (collectionView.tag == 100) {

        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionViewCell" forIndexPath:indexPath];

        

        cell.backgroundColor = [UIColor colorWithRed:arc4random() % 10 * 0.1 green:arc4random() % 10 * 0.1 blue:arc4random() % 10 * 0.1 alpha:1];

        

        return cell;

    }else if (collectionView.tag == 200) {

        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCollecionViewCell" forIndexPath:indexPath];

        

        cell.backgroundColor = [UIColor colorWithRed:arc4random() % 10 * 0.1 green:arc4random() % 10 * 0.1 blue:arc4random() % 10 * 0.1 alpha:1];

        

        return cell;

    }

    

    return nil;

}



//動態地設置單元格的尺寸

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

{

    return CGSizeMake(80, arc4random() % 80);

}





@end


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章