完全静态的 UICollectionView 可能吗?

Is completely static UICollectionView possible?

在 UITableView 中,完全静态的 tableView 配置是可能的。您可以断开 UITableView 的数据源并使用 IB 将每个单元格放在故事板(或 xib)上。

我用 UICollectionView 尝试过同样的事情。断开 UICollectionView 的数据源。将每个单元格放在故事板上的 UICollectionView 上。我构建它没有任何错误。但它没有用。单元格根本没有显示。

没有数据源的UICollectionView可以吗?

没有

不允许创建静态 UICollectionViewController。您必须有一个数据源委托。

我还要指出的是,不是静态的UITableView,而是静态的UITableViewController。就是不一样。

您可以轻松创建静态 UICollectionViewController。

只需在界面生成器中创建每个单元格,为它们提供可重复使用的标识符(例如 "Home_1" "Home_2" "Home_3"),然后按如下方式填充方法:

class HomeViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {  
    let cellIdentifiers:[String] = ["Home_1","Home_2","Home_3"]
    let sizes:[CGSize] = [CGSize(width:320, height:260),CGSize(width:320, height:160),CGSize(width:320, height:100)]

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cellIdentifiers.count
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifiers[indexPath.item], for: indexPath)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return sizes[indexPath.item]
    }
}

然后将视图控制器设置为适当的 class,然后,嘿,转瞬即逝,一个(基本上)静态集合。很遗憾地说,这是目前为止当您拥有一组控件时支持纵向和横向视图的最佳方式...

我做了一些试验并想添加我自己的方法,因为它帮助我实现了我一直在寻找的真正静态的、高度自定义的集合视图。

您可以为要在集合视图中显示的每个单元格创建自定义 UICollectionViewCells,并将它们注册到集合视图中的所有单元格 ID,如下所示:

创建静态单元格:

class MyRedCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.backgroundColor = .red
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

想做多少就做多少。

然后返回到您的 Collection View Controller 中,使用相应的 cellId 注册它们:

let cellIds = ["redCell","blueCell","greenCell"]

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.register(MyRedCell.self, forCellWithReuseIdentifier: "redCell")
    collectionView.register(MyBlueCell.self, forCellWithReuseIdentifier: "blueCell")
    collectionView.register(MyGreenCell.self, forCellWithReuseIdentifier: "greenCell")
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIds[indexPath.item], for: indexPath)

    return cell
}

每个单元格都会准确显示其 class 中的内容。