有一些关于UICollectionViews
的帖子,作为一般概念,我理解UICollectionViews
与TableViews
的实现方式类似。已经有一些关于此主题的帖子。
How to make a simple collection view with Swift
我正在使用 UICollectionView
布局 8 个单元格,主要用于装饰目的...就像一个容器,用于为一个页面保存一些图像。这些图像并不意味着是交互式的,例如。购物车
我的问题是,如果我在 Storyboard上布置我的单元格,是否需要实现下面的功能(以及其他类似功能)。
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
我在 Storyboard上配置的 UICollectionView
中有 8 个单元格(此 Collection View 是 UIViewController
上的 View )和每个 UICollectionViewCell
有一个带有 in 的 ImageView 。我已经把这些都放在 Storyboard上了。
我也不想在每个单元格中放一张图片。只是一定数量的细胞,例如。单元格 2、3、5 和 8。
所以我要做的是创建一个扩展 UIControllerViewCell
的类,并为 ImageView 创建一个 IBOutlet
,然后在界面构建器中引用自定义单元格类.
而且我认为 - 但可以做一些建议 - 然后我需要做的就是使用下面的函数,因为我只想填充某些单元格,所以我可以在索引路径为 2,3,5 时使用 if 语句和 8:
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if(indexPath == 2 || 3 || 5|| 8)
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell
// Use the outlet in our custom class to get a reference to the UILabel in the cell
cell.image = self.items[indexPath.item]
return cell
}
}
谢谢。
最佳答案
cellForItemAt
必须返回值(在这种情况下是 UICollectionViewCell
实例),但您可以自由地将某些单元格的图像设置为 nil
(又名无图像)
例如:
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MyCollectionViewCell
if([2,3,5,8].contains(indexPath.row))
{
// Use the outlet in our custom class to get a reference to the UIImageView in the cell
cell.myImageView.image = self.items[indexPath.row]
} else {
cell.myImageView.image = nil
}
return cell
}
关于swift - 如果在 Storyboard 中设置项目数,是否需要使用 numberOfItemsInSection 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46509866/