swift - Swift集合视图索引超出范围确定第一个单元格
问题描述
我正在尝试将第一个集合视图单元格设置为与我的其他单元格不同。我从 firebase 数据库中提取了一个帖子列表,并试图将第一个单元格创建为具有灰色背景的单元格,如下图所示,但我的索引超出了范围。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! HomeCell
if indexPath.row == 1 {
cell.backgroundColor = .lightGray
} else {
cell.list = lists[indexPath.item]
cell.contentView.layer.cornerRadius = 5.0
cell.contentView.layer.borderWidth = 1.5
cell.contentView.layer.borderColor = UIColor.clear.cgColor
cell.contentView.layer.masksToBounds = true
cell.layer.shadowColor = UIColor.lightGray.cgColor
cell.layer.shadowOffset = CGSize(width: 0, height: 2.0)
cell.layer.shadowRadius = 1.0
cell.layer.shadowOpacity = 1.0
cell.layer.masksToBounds = false
cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: cell.contentView.layer.cornerRadius).cgPath
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return lists.count + 1
}
解决方案
如果您需要不同
UIs
的CreateCell
andHomeCell
,则需要为此创建单独UITableViewCells
的。在
tableView(_:cellForItemAt:)
dequeue
类型的cell
基础上分开indexPath.row
。First row
在tableView
有indexPath as 0
和not 1
此外,您需要使用
self.lists[indexPath.row - 1]
而不是self.lists[indexPath.row]
配置HomeCell
这是我的意思的编译代码,
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.row == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CreateCell", for: indexPath) as! CreateCell
cell.backgroundColor = .lightGray
//configure your cell here...
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCell", for: indexPath) as! HomeCell
let list = self.lists[indexPath.row - 1]
//configure your cell with list
return cell
}
}
推荐阅读
- excel - Excel公式如果空白使用最后一个值作为常数
- mysql - 我是否保证在 mysql 中使用单个插入语句获得连续的 id?
- javascript - CodePen React Code 无法加载我的渐变背景
- c# - C# 为什么我无法打开 Windows 传真和扫描仪?
- python - 为什么我的程序会覆盖这两个对象?
- excel - Excel VBA 如果单元格(x,J)。价值=价值
- arrays - 在 postgres 中创建另一个表和使用数组有什么区别
- python-2.x - python 2 / list / if 语句 / 用户输入
- javascript - 使用 history.push() 到相同的组件但不同的 url 时重新渲染组件
- c - 如何在函数实现中使用函数的函数参数?