首页 > 解决方案 > 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
}

图片

标签: swift

解决方案


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

  2. tableView(_:cellForItemAt:) dequeue类型的cell基础上分开indexPath.row

  3. First rowtableViewindexPath as 0not 1

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

推荐阅读