Swift集合视图索引超出范围确定第一个单元格

时间:2019-06-11 12:55:59

标签: swift

我试图将第一个集合视图单元格设置为与其他单元格不同。我从firebase数据库中提取了一个帖子列表,我试图将第一个单元格设置为具有灰色背景的create单元格,如下图所示,但索引超出范围。

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
}

pic

1 个答案:

答案 0 :(得分:1)

  1. 如果UIsCreateCell需要不同的HomeCell,则需要为此创建单独的UITableViewCells

  2. tableView(_:cellForItemAt:) dequeue中,cell的类型基于indexPath.row

  3. First row中的
  4. tableView具有indexPath as 0not 1

  5. 此外,您需要使用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
    }
}