UICollectionView动态单元重叠问题

时间:2017-05-08 19:26:14

标签: ios swift uicollectionview uicollectionviewcell uicollectionviewlayout

我已经通过编程方式创建了UICollectionView水平滚动。 UICollectionView单元格宽度是根据内容动态创建的。

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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath) as! CustomCollectionViewCell
    cell.label.text = dataSource[indexPath.item]
    cell.label.font = UIFont(name: "Helvetica", size: 20.0)

    if currentPageIndex == indexPath.item {

        cell.currentPageIndicator.frame = CGRect(x: 0, y: cell.bounds.height - 2, width: cell.bounds.width, height: 2.5)
        cell.currentPageIndicator.isHidden = false
    }

    return cell

}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if let size = cellSizeCache.object(forKey: indexPath as AnyObject) as? NSValue {
        return size.cgSizeValue
    }

    let string = dataSource[indexPath.item]
    let height = collectionView.frame.size.height
    let font = UIFont(name: "Helvetica", size: 20.0)
    var size = string.boundingRect(with: CGSize(width: CGFloat.infinity, height: height), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font!], context: nil).size

    size.width += 20
    size.height += 20

    return size

}

最初,UICollectionView看起来很好,即使我水平滚动也是如此。 enter image description here 当我开始快速滚动时,单元格彼此重叠。 enter image description here

1 个答案:

答案 0 :(得分:0)

您的单元格重叠,因为单元格的宽度小于内容的大小。您有两个选项,第一个选项是增加故事板中单元格的宽度。第二个选项是在collectionview方法中为每个单元格设置名为“sizeforcellatindexpath”的大小,示例方法如下:

    optional func collectionView(_ collectionView: UICollectionView,
              layout collectionViewLayout: UICollectionViewLayout,
         sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

     return size

    }

您可以使用计算机制计算字符串的大小。收集样品如下:

How to calculate the width of a text string of a specific font and font-size?