寫到這裡才真正體會到,UICollectionView 的用法其實和 UITableView 十分相似,掌握其中一者,另一者也就觸類旁通了。
如果你使用的是 Storyboard,在製作過程中一定要特別留意 datasource 與 delegate 的連接,以及一些自訂元件與 Storyboard 裡的連線是否正確。
先從 ViewController 裡拖曳一個 CollectionView 進來,取消勾選 Use Autolayout。CollectionView 本身就內建了一個 cell,接下來就是自訂 cell 的程式碼。這裡介紹第一種做法:不建立獨立的 cell 類別,但你必須標記好 cell 內每個控件的 tag 值。
如下:
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
return 6; // 返回 6 個項目
}
// 這個方法很關鍵,可搭配字典型 layout 使用
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"imgCell" forIndexPath:indexPath];
UILabel *titleLabel = (UILabel *)[cell viewWithTag:11];
NSString *sttr = [[NSString alloc] initWithFormat:@"Hello~%d", indexPath.row];
[titleLabel setText:sttr];
return cell;
}
// 向下一個視圖傳值
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:@"showDetail"]) {
// 在這裡處理傳值邏輯
}
}
其中 cellForItemAtIndexPath 是最關鍵的方法,透過它我們可以為每個 item 配置對應的內容。若需要自訂 cell 樣式,也可以建立獨立的 UICollectionViewCell 子類,那將是下一篇要介紹的第二種方法。