很久沒更了,感覺學(xué)習(xí)的很基礎(chǔ)的東西沒什么好寫的,網(wǎng)上也一大把,但是發(fā)現(xiàn)寫博客的一大好處就是,你忘記了一個知識點可以翻開博客查找,還是得堅持.
UICollectionView代碼創(chuàng)建
簡介:
??UICollectionView是UIScrollView的子類,顯示一組 UICollectionCell 或其子類
??UICollectionViewController有數(shù)據(jù)源,委托 (UICollectionViewDelegate),布局類
??1.數(shù)據(jù)源:UICollectionViewController.返回幾行幾列等方法
??2.委托:UICollectionViewDelegate,哪一列被點擊打等方法.
??3.布局類:為每個 Cell 布局,如果想按網(wǎng)格布局,則可以使用 UICollectionViewFlowLayout,如果想自定義布局,可以創(chuàng)建 UICollectionViewLayout 的自定義子類.
UICollectionViewCell的 contentView 默認(rèn)是沒有子試圖的,所以需要自定義 創(chuàng)建UICollectionViewCell的子類,來添加你想用來顯示的東西
創(chuàng)建步驟
網(wǎng)上很多教程都直接在 ViewDidLoad 中創(chuàng)建,但是好像并沒什么用,具體細(xì)節(jié)還有待深究,我的做法是直接將 ViewController 的 view 設(shè)置為 CollectionView(創(chuàng)建 UICollectionViewController 文件,并且設(shè)置為原始 viewController 的類)
- 聲明一個全局變量 UICollectionView *coll,在 loadView 創(chuàng)建
UICollectionView,和 UICollectionViewFlowOut - (void)loadView { UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; _coll = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 500, 500) collectionViewLayout:layout]; self.view = _coll; _coll.backgroundColor = [UIColor whiteColor]; }
2.viewDidLoad 中注冊 Cell ,以便重用,并且設(shè)置數(shù)據(jù)源和 DataSource代理為自己
- (void)viewDidLoad { [super viewDidLoad];
_coll.delegate = self;
_coll.dataSource = self;
// Register cell classes
[_coll registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier];
// Do any additional setup after loading the view.
}
3.設(shè)置數(shù)據(jù)源
#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 4;
}
//注冊 Cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor blueColor];
return cell;
}
4.布局可以實現(xiàn)在FlowOut 協(xié)議中的方法來設(shè)置 item 大小,外邊距等,這個可以看下文檔實現(xiàn),到這里基本的代碼構(gòu)建就完成了
UICollectionView 和 UITableView 的不同之處
1.最大的不同在于,UITableView 只顯示UITableViewCell 一列,而 UICollectionView 可以任意安排 UICollectionCell
2.UICollectionCell 的 contentView 沒有子試圖,需要自定義,UITableViewCell 可以用默認(rèn)的
其他倒是都差不多
歡迎交流學(xué)習(xí):ykkaixing@gmail.com