当我使用两种不同类型的单元格并且其中一个单元格的大小始终为一个时,如何确定大小集合视图,而另一个单元格的大小取决于数组,因此它的大小是动态的。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if indexPath.row == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProfileCell", for: indexPath) as! ProfileCollectionViewCell
            cell.bioLabelText.text = bio
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CountryCollectionViewCell

            cell.countryLabel.text = city
            cell.imgView.image = UIImage(named: "lake.jpg")
            cell.makeRounded()
            return cell
        }
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return uniqueCountryArray.count

    }

我的ProfileCell编号应为1,其他单元格的编号应为uniqueCountryArray.count。但是,当我写“return uniqueCountryArray.count + 1”时,它给了我错误。当我写“return uniqueCountryArray.count”时,我错过了一个数组元素。

如何动态获取所有数组元素?而且id数组大小为0,我仍然应该显示I cell来自配置文件Cell。

最佳答案

将您的city = uniqueCountryArray[indexPath.row]更改为city = uniqueCountryArray[indexPath.row-1],如下所示

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if indexPath.row == 0 {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProfileCell", for: indexPath) as! ProfileCollectionViewCell
        cell.bioLabelText.text = bio
        return cell
    }
    else {

        let city = uniqueCountryArray[indexPath.row-1]

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CountryCollectionViewCell
        cell.countryLabel.text = city
        cell.imgView.image = UIImage(named: "lake.jpg")
        cell.makeRounded()
        return cell
    }
}

numberOfItemsInSection将为uniqueCountryArray.count+1
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return uniqueCountryArray.count+1
}

08-27 11:31