您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 自訂 UICollectionView 版面:伸縮流水與圓形排列

編輯:iOS 開發綜合

瀑布流是電商類 App 展示商品最常見的版型,如下圖。

實作方式大致有三種:

  • 用 UITableView(少見)
  • 用 UITableView 或 UIScrollView 手刻(工作量大)
  • 用 UICollectionView(主流做法)

一、UICollectionView 基礎

它與 UITableView 有不少相似之處:都由 data source 提供資料、由 delegate 處理事件、都支援自訂 cell 與重用機制、也都繼承自 UIScrollView 因而具備滾動能力。

差異在於:UICollectionView 必須搭配一個 UICollectionViewLayout(通常是 UICollectionViewFlowLayout)或其子類來決定版面;而我們正是可以繼承 Layout,自行定義滾動方向與 cell 的排列規則。UICollectionViewFlowLayout 就是所謂的流水佈局,也是最常用的一種。

二、自訂 Layout 的常用方法

佈局初始化:

- (void)prepareLayout {
    // 在此完成佈局初始化
}

尺寸變動時是否重算:

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;   // 預設即為 YES
}

回傳指定矩形區域內所有元素的佈局屬性,以及單一元素的佈局屬性:

- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)
    layoutAttributesForElementsInRect:(CGRect)rect {
    // 需回傳 rect 區域內所有元素的佈局屬性
}

- (nullable UICollectionViewLayoutAttributes *)
    layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 回傳 indexPath 位置元素的佈局屬性
}

控制停止滾動時的最終偏移量(常用於「吸附置中」效果):

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
                                   withScrollingVelocity:(CGPoint)velocity {
    // 回傳值即為 UICollectionView 最終停留的點
}

三、完整範例

此範例的設計:以 UICollectionView 為基礎,實作「橫向伸縮流水」與「圓形排列」兩種自訂版面;點擊 cell 可將其刪除;點擊控制器主視圖則在兩種版面之間切換。

1. 橫向伸縮流水佈局

初始化時設定橫向滾動與左右內嵌,讓頭尾留白:

- (void)prepareLayout {
    [super prepareLayout];
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width) * 0.5;
    self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
}

核心效果:以 collectionView 中點為基準,離中點越遠的 cell 縮得越小,形成透視般的伸縮感:

- (nullable NSArray<UICollectionViewLayoutAttributes *> *)
    layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *array = [super layoutAttributesForElementsInRect:rect];

    // 以 contentView 左上角為原點,算出 collectionView 的中點
    CGFloat centerX = self.collectionView.contentOffset.x
                    + self.collectionView.frame.size.width * 0.5;

    for (UICollectionViewLayoutAttributes *attribute in array) {
        CGFloat delta = ABS(attribute.center.x - centerX);
        CGFloat scale = 1 - delta / self.collectionView.bounds.size.width;
        attribute.transform = CGAffineTransformMakeScale(scale, scale);
    }
    return [array copy];
}

再讓滾動停止時自動吸附,使最接近中點的 cell 精準置中:

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset
                                   withScrollingVelocity:(CGPoint)velocity {
    CGRect rect;
    rect.origin = CGPointMake(proposedContentOffset.x, 0);
    rect.size = self.collectionView.frame.size;

    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    CGFloat centerX = proposedContentOffset.x
                    + self.collectionView.frame.size.width * 0.5;

    CGFloat minDelta = MAXFLOAT;
    for (UICollectionViewLayoutAttributes *attribute in array) {
        CGFloat delta = attribute.center.x - centerX;
        if (ABS(minDelta) > ABS(delta)) {
            minDelta = delta;
        }
    }
    proposedContentOffset.x += minDelta;
    return proposedContentOffset;
}

2. 圓形排列佈局

用一個陣列快取所有元素的佈局屬性,並以懶載入建立:

@property (nonatomic, strong) NSMutableArray *attrsArray;

- (NSMutableArray *)attrsArray {
    if (_attrsArray == nil) {
        _attrsArray = [NSMutableArray array];
    }
    return _attrsArray;
}

每次 prepareLayout 都清掉舊值並重算全部元素:

- (void)prepareLayout {
    [super prepareLayout];
    [self.attrsArray removeAllObjects];

    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    for (NSInteger i = 0; i < count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attrs =
            [self layoutAttributesForItemAtIndexPath:indexPath];
        [self.attrsArray addObject:attrs];
    }
}

以圓心與半徑,用三角函數把元素均勻分佈在圓周上:

- (nullable UICollectionViewLayoutAttributes *)
    layoutAttributesForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    NSInteger count = [self.collectionView numberOfItemsInSection:0];

    CGFloat radius = 70;
    CGFloat oX = self.collectionView.frame.size.width * 0.5;
    CGFloat oY = self.collectionView.frame.size.height * 0.5;

    UICollectionViewLayoutAttributes *attrs =
        [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attrs.size = CGSizeMake(50, 50);

    if (count == 1) {
        attrs.center = CGPointMake(oX, oY);
    } else {
        CGFloat angle = (2 * M_PI / count) * indexPath.item;
        CGFloat centerX = oX + radius * sin(angle);
        CGFloat centerY = oY + radius * cos(angle);
        attrs.center = CGPointMake(centerX, centerY);
    }
    return attrs;
}

- (nullable NSArray<UICollectionViewLayoutAttributes *> *)
    layoutAttributesForElementsInRect:(CGRect)rect {
    return self.attrsArray;
}

3. 以 xib 製作 cell

@property (nonatomic, copy) NSString *imageName;

- (void)awakeFromNib {
    // 用 Layer 加上白邊與圓角
    self.imageView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.imageView.layer.borderWidth = 6;
    self.imageView.layer.cornerRadius = 3;
}

- (void)setImageName:(NSString *)imageName {
    _imageName = [imageName copy];
    self.imageView.image = [UIImage imageNamed:imageName];
}

4. 準備圖片資料

@property (nonatomic, strong) NSMutableArray *imageNames;

- (NSMutableArray *)imageNames {
    if (_imageNames == nil) {
        NSMutableArray *imageNames = [NSMutableArray array];
        for (NSInteger i = 0; i < 20; i++) {
            [imageNames addObject:[NSString stringWithFormat:@"%zd", i + 1]];
        }
        _imageNames = imageNames;
    }
    return _imageNames;
}

5. 建立 collectionView

用 weak 屬性保存,方便隨時替換 layout:

@property (nonatomic, weak) UICollectionView *collectionView;

- (void)setupCollectionView {
    CGFloat collectionViewW = self.view.bounds.size.width;
    CGFloat collectionViewH = 200;
    CGRect frame = CGRectMake(0, 150, collectionViewW, collectionViewH);

    LYPCircleLayout *layout = [[LYPCircleLayout alloc] init];
    UICollectionView *collectionView =
        [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
    self.collectionView = collectionView;

    collectionView.dataSource = self;
    collectionView.delegate = self;
    [self.view addSubview:collectionView];
}

6. 資料來源

/** 重用識別碼 */
static NSString *const ID = @"photo";

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupCollectionView];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LYPPhotoCell class])
                                                 bundle:nil]
              forCellWithReuseIdentifier:ID];
}

- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {
    return self.imageNames.count;
}

- (UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView
                  cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    // 有回收就重用,沒有則自動建立
    LYPPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID
                                                                 forIndexPath:indexPath];
    cell.imageName = self.imageNames[indexPath.item];
    return cell;
}

7. 點擊刪除

- (void)collectionView:(nonnull UICollectionView *)collectionView
didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    [self.imageNames removeObjectAtIndex:indexPath.item];
    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
}

8. 點擊空白處切換版面

- (void)touchesBegan:(nonnull NSSet<UITouch *> *)touches
           withEvent:(nullable UIEvent *)event {
    if ([self.collectionView.collectionViewLayout isKindOfClass:[LYPLineLayout class]]) {
        // 目前是流水佈局 → 切換成圓形佈局
        [self.collectionView setCollectionViewLayout:[[LYPCircleLayout alloc] init] animated:YES];
    } else {
        // 目前是圓形佈局 → 切換成流水佈局
        LYPLineLayout *layout = [[LYPLineLayout alloc] init];
        // 不設定 itemSize 則會自動計算
        layout.itemSize = CGSizeMake(130, 130);
        [self.collectionView setCollectionViewLayout:layout animated:YES];
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved