重新加载集合视图时会发生这种情况

时间:2019-05-30 10:27:57

标签: swift layout collectionview reloaddata

enter image description here

我正在根据其中的字符串设置集合视图单元格的大小。我使用此代码,并且第一次成功,第二次或更多次重新加载集合视图时,会发生这种情况(请参见图片)

这是我的代码:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        var i:Int = 0
        var size = CGSize()

        for t in mainCategoryDic {
            if(i == indexPath.row) {
                let index:String = t.key
                size = (mainCategoryDic[index]?.name?.size(withAttributes: [NSAttributedString.Key.font : UIFont(name:font_name, size: 14)!]))!
            }
            i += 1
        }

        return CGSize(width: size.width + 38.0, height: 30.0)
    }

1 个答案:

答案 0 :(得分:1)

尝试一下:

   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        var size = CGSize()
        let t = mainCategoryDic[indexPath.item]
        let index: String = t.key
        size = (mainCategoryDic[index]?.name?.size(withAttributes: [NSAttributedString.Key.font : UIFont(name:font_name, size: 14)!]))!
        return CGSize(width: size.width + 38.0, height: 30.0)
    }