您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS UICollectionView 初學指南:Storyboard、Cell 與資料傳遞

編輯:iOS 相關資訊

從 UITableView 到 UICollectionView

對熟悉 UITableView 的開發者來說,UICollectionView 的資料來源與委派概念並不陌生。它同樣以 section 與 item 為核心,透過 dequeue 機制重用 Cell,並由 view controller 提供每一格要顯示的內容。

Storyboard 的關鍵設定

若使用 Storyboard,最重要的步驟是確認 delegate 與 datasource 有正確連線到 view controller,也別忘了 collection view 與自訂 cell 的 identifier 要一致。若沒有使用 Auto Layout,也要先取消勾選,避免後續 frame 計算被系統接管。

不用自訂 Cell 類別的簡易做法

如果 Cell 內部元件不複雜,可以直接在 Cell 上為每個子檢視設定 tag,再利用 viewWithTag 取得元件。這種方式適合快速驗證畫面,但正式專案仍建議建立獨立 Cell 類別,讓資料綁定更清楚。

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
    return 6;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"imgCell" forIndexPath:indexPath];
    UILabel *titleLabel = (UILabel *)[cell viewWithTag:11];
    NSString *sttr = [NSString stringWithFormat:@"Hello~%d", indexPath.row];
    [titleLabel setText:sttr];
    return cell;
}

向下一個視圖傳值

當 Cell 被點選並觸發 segue 時,可在 prepareForSegue 中判斷 segue identifier,再把 indexPath 或模型物件傳給目標 controller。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDetail"])
    {
        // 在這裡把資料傳給下一個視圖
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved