iOS通过storyboard创建UICollectionViewController

227 阅读2分钟

1.什么是UICollectionViewController

UICollectionViewControllerUIKit中的一个视图控制器,专门用于管理基于网格或瀑布流布局的界面。它继承自UIViewController,并通过集成的UICollectionView来实现数据的展示和管理。

2.创建UICollectionViewController

要使用UICollectionViewController,可以按照以下步骤创建一个简单的集合视图界面:

  1. 在Xcode中,创建一个新的UICollectionViewController子类,例如MyCollectionViewController
  2. 打开Main.storyboard,拖拽一个UICollectionViewController到您的界面中,并将其与刚才创建的类进行关联(在Identity Inspector中设置Class)。
  3. Attributes Inspector中,配置集合视图的外观和布局属性。

iShot_2023-08-18_15.10.38.png iShot_2023-08-18_15.10.45.png iShot_2023-08-18_15.02.49.png iShot_2023-08-18_15.11.49.png iShot_2023-08-18_15.22.20.png

3.数据源和代理方法

UICollectionViewController 依赖于数据源和代理方法来管理内容和交互。以下是一些常用的数据源和代理方法:

-   numberOfSections(in collectionView: UICollectionView) -> Int:返回集合视图的分区数量
-   numberOfSections(in collectionView: UICollectionView) -> Int:返回每个分区中的项数
-   collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell:返回指定索引路径的单元格
-   collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath):处理单元格的点击事件

4.不同的布局

UICollectionViewController支持多种布局,包括:

  • 流式布局(Flow Layout):类似于UITableView的列表布局,可用于创建横向或纵向滚动的网格界面。
  • 自定义布局:通过继承UICollectionViewLayout,您可以创建完全自定义的布局,如瀑布流、圆形布局等。
  • 组合布局:结合多种布局,创建更复杂的界面。

5.适用场景

UICollectionViewController适用于多种应用场景,包括但不限于:

  • 图片浏览器:创建可滚动的图片网格,支持缩放和查看大图。
  • 商品展示:展示商品列表,支持不同布局和过滤条件。
  • 照片墙:类似于社交媒体的照片墙,支持用户上传和浏览照片。
  • 瀑布流界面:实现Pinterest风格的瀑布流布局,展示不同大小的卡片。

6.示例:创建简单的网格界面

import UIKit

class MyCollectionViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // 数据源和代理方法
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "colorCell", for: indexPath)
        cell.backgroundColor = randomColor()
        return cell
    }

    // 生成随机颜色
    func randomColor() -> UIColor {
        let red = CGFloat.random(in: 0...1)
        let green = CGFloat.random(in: 0...1)
        let blue = CGFloat.random(in: 0...1)
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
}

  1. Storyboard中,选中UICollectionViewController,然后在右侧的Attributes Inspector中找到"Prototype Cells",将Items设置为1。
  2. Storyboard中,点击Prototype Cell,然后在右侧的Attributes Inspector中设置Identifier"colorCell"
  3. 运行的app,将看到一个简单的网格界面,其中包含10个随机颜色的方块。

iShot_2023-08-18_17.13.56.png

文章结束。