【发布时间】:2015-02-06 05:12:59
【问题描述】:
试图了解集合视图、数组和字典。我有一个名为 CollectionViewCell 的类,其中包含一个 UIImageView 插座,我希望从数组中填充图像。问题是我有不同内容的不同部分,所以我创建了多个存储图像的数组。使用当前代码,我收到一条错误消息,指出数组索引超出范围。我是否需要用一个字典来填充不同的部分,用键和值来分隔信息?
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as CollectionViewCell
// Configure the cell
cell.imageView.image = green[indexPath.row]
cell.imageView.image = blue[indexPath.row]
return cell
如何使用从数组填充的标题来命名不同的部分? names 是我的字符串数组, HeaderView 是一个包含空标签的类。使用此代码时我也遇到了错误。
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView =
collectionView.dequeueReusableSupplementaryViewOfKind(kind,
withReuseIdentifier: "HeaderView",
forIndexPath: indexPath)
as HeaderView
headerView.label.text = names[indexPath.row]
return headerView
default:
assert(false, "Unexpected element kind")
}
}
[编辑] 段码中的段数和项数:
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//Return the number of sections
return 2
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//Return the number of items in the section
return green.count
}
因此,如果蓝色部分中的项目数量与绿色部分不同,我是否也将 return blue.count 包含在 numberOfItemsInSection 函数中?
【问题讨论】:
-
绿色和蓝色是否应该填充不同的单元格?您能否也发布您的 collectionView:numberOfItemsInSection: 和 numberOfSectionsInCollectionView: 代码?
-
是的!绿色和蓝色在它们的数组中有不同的元素。
标签: ios arrays swift dictionary collectionview