網格視圖

import "ViewController.h"

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
UICollectionView *collection; //網格視圖
}

@end

//設置可重用標識符
static NSString * const reuseID = @"cell";

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    //創建一個布局對象
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init];

    //設置每個格子的大小
    flowlayout.itemSize = CGSizeMake(100, 100);

    //設置每個格子的最小水平間距
    flowlayout.minimumInteritemSpacing = 20;

    //設置行間距 最小行間距
    flowlayout.minimumLineSpacing = 20;

    //設置組與組之間的間隔
    flowlayout.sectionInset = UIEdgeInsetsMake(50, 10, 0, 10);
    //創建網格對象
    collection = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:flowlayout];

    //設置代理
    collection.delegate = self;
    collection.dataSource = self;

    //設置網格背景顏色
    collection.backgroundColor = [UIColor greenColor];

    //注冊cell
    [collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseID];

    //將網格添加到父視圖上
    [self.view addSubview:collection];
    }

//=========數據源方法=========

//設置組數

  • (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
    {
    return 5;
    }

//設置行數

  • (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
    {
    return 5;
    }

//設置 cell 內容

  • (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
//根據可重用標識符查找cell
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];

//設置cell的背景顏色
cell.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0)green:((float)arc4random_uniform(256) / 255.0)blue:((float)arc4random_uniform(256) / 255.0)alpha:1.0];

return cell;

}

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

推薦閱讀更多精彩內容