UICollectionViews
上有一些帖子,作为一般概念,我了解UICollectionViews
与如何实现TableViews
相似。已经有一些有关此主题的帖子。
如何使用Swift
进行简单的收集视图我正在使用UICollectionView
来布局8个单元格,用于装饰目的……就像一个容器可以容纳一些图像。这些图像并不是要交互式的,例如。购物车。
我的问题是,如果我在情节提要上铺设了我的单元格,我是否需要在下面的功能(以及其他类似的功能)。
// tell the collection view how many cells to make
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
我在故事板上配置的UICollectionView
中有8个单元格(此收集视图是UIViewController
上的视图),并且每个UICollectionViewCell
都具有In。P>
我也不想在每个单元格中放置图像。只是一定数量的卡尔,例如。细胞2,3,5和8。
所以我要做的就是创建一个延伸UIControllerViewCell
并为图像视图创建IBOutlet
的类,然后在接口构建器中引用自定义单元格类。
我想 - 但是可以做一些建议 - 然后我要做的就是使用下面的功能,因为我只想填充某些单元格,所以当它是2,3,5和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
(aka no image)
eg:
// 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
}
听起来您在询问静态的uicollectionViewController,这是不可能的。您将在情节板上创建一个原型单元格,并将IBOUTLET与所需的类链接。您还需要为UicollectionView实现数据源和委派方法。只需将图像隐藏您不想根据索引显示的位置。